12/18 Anonymous Functions Python 3


#1

I understand how the syntax works in this tutorial, when working in python 2, since I’m using python 3 I like to test out some of the tutorials in the python installed on my computer to see how it compares and works.
So I stat by making my list

>>> my_list=[x for x in range(0,16)]

I then check I have what I expected

>>> print(my_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Now I try and filter out only the numbers divisible by 3 and I get the following:

>>> print(filter(lambda x: x % 3 == 0, my_list))
<filter object at 0x000001DEED7ECA20>

Could somebody help guide me towards how I would do this in Python 3, using the logic in the tutorial, such that I get :

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

As my desired output

This is the tutorial:

https://www.codecademy.com/courses/learn-python/lessons/advanced-topics-in-python/exercises/anonymous-functions?action=lesson_resume


#2
>>> my_list=[x for x in range(0,16)]
>>> print(my_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> print(list(filter(lambda x: x % 3 == 0, my_list)))
[0, 3, 6, 9, 12, 15]
>>> 

Where Python 2 would return a list from functions like range, map, filter, etc., Python 3 returns an iterable. To see the list, we need to cast it as a list.

This is actually a fairly straight forward example of filter() and lambda. We could get the same result with just using the list comprehension:

>>> my_list=[x for x in range(0,16, 3)]
>>> my_list
[0, 3, 6, 9, 12, 15]
>>> 

Aside

I gave your topic a vote because you were good enough to include a link to the exercise. Thanks.


#3
>>> list(filter(lambda x: len(x) > 2, "fish in a barrel".split()))
['fish', 'barrel']
>>> 

The above explores a scenario that might not be ordered or predictible.

>>> for x in filter(lambda x: len(x) > 2, "fish in a barrel".split()):
	print(x)

	
fish
barrel
>>> 

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.