Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Within Filter Function?

I found this tutorial on using lambda within python. Upon attempting to do the 3rd example I've discovered the results are not the same as in the tutorial. I'm 99% sure my code is correct, but here it is nonetheless.

my_list = [2,9,10,15,21,30,33,45]

my_new_list = filter(lambda x: x % 3 == 0, my_list)
print(my_new_list)

The result of this is: <filter object at 0x004F39F0>

Things to keep in mind:

  • I'm using Python 3.4.2
  • Using Python 2.7.2 work fine and returns [9, 15, 21, 30, 33, 45]

I understand that it simply doesn't work in Python 3.4+; I'm more curious as to why it doesn't work and also looking for an equal way of doing this, with or without lambda.

like image 818
A Magoon Avatar asked Mar 15 '26 03:03

A Magoon


2 Answers

The difference in output is caused by the fact that filter returns an iterator in Python 3.x. So, you need to manually call list() on it in order to get a list:

>>> my_list = [2,9,10,15,21,30,33,45]
>>> filter(lambda x: x % 3 == 0, my_list)
<filter object at 0x01ACAB50>
>>> list(filter(lambda x: x % 3 == 0, my_list))
[9, 15, 21, 30, 33, 45]
>>>

The same goes for map, which was also changed in Python 3.x to return an iterator. You can read about these changes here: https://docs.python.org/3/whatsnew/3.0.html#views-and-iterators-instead-of-lists


That said, filter and map are generally disliked by Python programmers. Especially so if you need to use a lambda with them. A better approach in this case (and pretty much all others) would be to use a list comprehension:

my_list = [2,9,10,15,21,30,33,45]

my_new_list = [x for x in my_list if x % 3 == 0]
print(my_new_list)

It's because in Python 3, the filter function returns an iterator. Use list(my_new_list) to get all the results. To be clear, it's not that filter "doesn't work", but that it's behavior is different in Python 3.x compared to 2.x.

See How to use filter, map, and reduce in Python 3 for a previous answer.

The reasoning behind this is that if you have a large list, processing all the elements right away may not be desirable. The generator will produce results on demand, letting you save memory in the case that you only end up using part of the result (e.g. if iterating through the filtered list).

like image 28
li.davidm Avatar answered Mar 16 '26 15:03

li.davidm



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!