+ 3

Difference between list filter vs comprehension condition

nums=[4,1,6,8,3,34,357] print(list(filter(lambda x: x%2==0, nums))) print([x for x in nums if x%2==0] ) https://code.sololearn.com/czu16A9WRqrA/?ref=app The result of the 2 print lines seems to be the same. Are there differences between the 2 methods? Is one way more memory efficient or are they exactly the same?

6th Jan 2022, 7:43 AM
Sandy Ho
Sandy Ho - avatar
2 Antworten
+ 3
There ist always more than one way. In this case I would choose the second one, because of is more pythonic. You can test the running time of the Algorithmus if speed is important https://code.sololearn.com/cXSv2ranbv6x/?ref=app
6th Jan 2022, 9:02 PM
Sebastian Keßler
Sebastian Keßler - avatar
+ 1
Those are interesting tests, I have learn something new! Thanks for sharing!
6th Jan 2022, 9:22 PM
Sandy Ho
Sandy Ho - avatar