A Magoon
A Magoon

Reputation: 1210

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 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.

Upvotes: 2

Views: 1163

Answers (2)

user2555451
user2555451

Reputation:

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)

Upvotes: 9

li.davidm
li.davidm

Reputation: 12116

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).

Upvotes: 4

Related Questions