James Hallen
James Hallen

Reputation: 5014

If statement in lambdas Python

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?

Upvotes: 2

Views: 406

Answers (3)

johnsyweb
johnsyweb

Reputation: 141810

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.

Upvotes: 2

Sukrit Kalra
Sukrit Kalra

Reputation: 34493

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']

Upvotes: 13

zhangyangyu
zhangyangyu

Reputation: 8610

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']
>>> 

Upvotes: 2

Related Questions