first filter() argument as list comprehension? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

first filter() argument as list comprehension?

Hello alltogether Can someone please shed some light on my thoughts please. Can the Lambda func in the following codesnippet substituted with a list comprehension in some way? As I understand it, the filter() func needs a func as first argument and a list comprehension would be a list object and not a func object. I am wondering now if there is some elegant way to substitude the Lambda func with a list compr. anyway. nums = [11, 22, 33, 44, 55] res = list(filter(lambda x: x%2==0, nums)) print(res)

13th Feb 2019, 5:36 AM
Bela
Bela - avatar
5 Answers
+ 4
res = [ x for x in nums if x%2==0 ]
13th Feb 2019, 5:43 AM
Gordon
Gordon - avatar
+ 4
The filter() function itself is said to be "unpythonic" because a list comprehension does exactly the same in a more obvious way. So you could argue that using the filter function isn't elegant, much less using a list comprehension as an argument for the filter function. Why would you want to do that? 🤔
13th Feb 2019, 6:01 AM
Anna
Anna - avatar
+ 4
Allow me to clarify some issues with filter and list comprehension 1. Explicit function The first argument does not have to be lambda function <-- CORRECT It can be an explicit function. https://code.sololearn.com/c4zQI01yPm9W/?ref=app https://code.sololearn.com/c06bVu0UOOS2/?ref=app https://code.sololearn.com/cETCb20aM5P1/?ref=app 2. List comprehension can accept tuple. But if you make output tuple it'll be a generator https://code.sololearn.com/cIXh30zKfHrL/?ref=app 3. When the logic is simple condition, list comprehension is same as filter. https://code.sololearn.com/cg7Ncf22uO5V/?ref=app 4. But actually list comprehension is more flexible https://code.sololearn.com/c8lDV6FtY2ZD/?ref=app
13th Feb 2019, 9:17 AM
Gordon
Gordon - avatar
+ 1
nice & short Thx for your answer Gordon Do you can think of any way of putting a list compr. as the first argument of the func filter() and just substitute the Lambda func?
13th Feb 2019, 5:56 AM
Bela
Bela - avatar
+ 1
Hi Anna Makes sense what you say. Thx for your input. Me toying around with list comprehensions and collecting different samples. I still need some time to get comfortable with them.
13th Feb 2019, 6:07 AM
Bela
Bela - avatar