Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement in lambdas Python

Tags:

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?

like image 404
James Hallen Avatar asked Feb 26 '26 07:02

James Hallen


1 Answers

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']
like image 169
Sukrit Kalra Avatar answered Feb 28 '26 19:02

Sukrit Kalra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!