Anonymous functions in python 3 very different


Okay I am doing the Python 2 codecademy class and I came to the anonymous functions, while I get what it all means it seems to work very different in my Python 3 PyCharm. I am not sure and would love if someone helped.

Here is the code that had been given to me during the lecture

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

this is the result in the lecture environment (python 2.x)

[0, 3, 6, 9, 12, 15]

this is the result in the Pycharm 3.7 environment

<filter object at 0x000001A1BE4183C8>

What? :smiley:


Where the Python 2 iterators used to return a list, they now return their own object. We can still iterate over them, but if we wish to print them we need to cast them as a list.

print (list(filter(...)))

The same applies to range(). It too needs to be cast as a list for printing purposes.


Note the title …

The anonymous function is the lambda, and that is the same in Python 2 and Python 3. As @mtf has pointed out, the filter function, which returns an iterator, is what accounts entirely for the different behavior that you noticed between the two versions of Python.


Thank you boys, now one question. I have read a bit about these lambda functions, about the fact that the founder wanted them to be gone for good, that someone hates them etc. etc. How do you two use them, how do you found them useful. I would love to hear some opinion.


A lambda is useful in a situation where you need a function that you only intend to use in one place, and where it can be written in one line of code. Rather than clutter up your code with lots of short named functions that you use only once, you can define a lambda right where it is needed, for example, where you pass it as an argument to another function. In the current case, you needed a short function solely as an argument to the filter function, and that is your lambda.

EDIT (The following was added on December 6, 2018.)

As an alternative to defining an anonymous function in the current context, you could have done this, however the submission correctness test (SCT) for the exercise might not have accepted it …

def is_divisible_by_three(x):
    return x % 3 == 0

print(list(filter(is_divisible_by_three, my_list)))

Note that in the above, the code was adapted for Python 3.x.


Thanks a lot for the info mate. Cheers