2

I wanted to declare an if statement inside a lambda function:

Suppose:

cells = ['Cat', 'Dog', 'Snake', 'Lion', ...]
result = filter(lambda element: if 'Cat' in element, cells)

Is it possible to filter out the 'cat' into result?

James Hallen
  • 4,534
  • 4
  • 23
  • 28

3 Answers3

13

If you want to filter out all the strings that have 'cat' in them, then just use

>>> cells = ['Cat', 'Dog', 'Snake', 'Lion']
>>> filter(lambda x: not 'cat' in x.lower(), cells)
['Dog', 'Snake', 'Lion']

If you want to keep those that have 'cat' in them, just remove the not.

>>> filter(lambda x: 'cat' in x.lower(), cells)
['Cat']

You could use a list comprehension here too.

>>> [elem for elem in cells if 'cat' in elem.lower()]
['Cat']
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
2

The element means the elements of the iterable. You just need to compare.

>>> cells = ['Cat', 'Dog', 'Snake', 'Lion']
>>> filter(lambda element: 'Cat' == element, cells)
['Cat']
>>> 

Or if you want to use in to test whether the element contains something, don't use if. A single if expression is syntax error.

>>> filter(lambda element: 'Cat' in element, cells)
['Cat']
>>> 
zhangyangyu
  • 8,520
  • 2
  • 33
  • 43
  • Are you sure that this is the intented behaviour? 'cause it looks pretty nonsense if understood like that. Or at least purposeless. Filtering an element that you can check with simple `in` operator? – luk32 Jul 26 '13 at 01:54
  • I am not sure. But according to OP's description, (s)he seems to want the behaviour like this. – zhangyangyu Jul 26 '13 at 01:55
  • Well, to me his description its not clear what he wants. There are way better solutions to do the task. Using `filter` for a single element seems kinda stupid. – luk32 Jul 26 '13 at 01:59
2

You don't need if, here. Your lambda will return a boolean value and filter() will only return those elements for which the lambda returns True.

It looks like you are trying to do either:

>>> filter(lambda cell: 'Cat' in cell , cells)
['Cat']

Or...

>>> filter(lambda cell: 'Cat' not in cell, cells)
['Dog', 'Snake', 'Lion', '...']

...I cannot tell which.

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] and it's more usual (Pythonic) to use the list comprehension for this pattern:

>>> [cell for cell in cells if 'Cat' in cell]
['Cat']
>>> [cell for cell in cells if 'Cat' not in cell]
['Dog', 'Snake', 'Lion', '...']

See List filtering: list comprehension vs. lambda + filter for more information on that.

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247