Map in Python

Just like in Snap!, Python allows us to operate on all of the items of a list by using Higher Order Functions (HOFs). In python we can perform a map operation that squares all of the numbers in a list by using the following syntax:


>>> my_list = [1, 2, 3]
                    

>>> def square(x):
...    return x * x
>>> map(square, my_list)
                    

Above you can see that the python code is very similar to the Snap! code. Instead of having a multiply function with two blanks, as in the Snap! version of map, we first define a square function and pass it as an argument to the map function. We could also create an anonymous function by using the lambda keyword, which acts a lot like the ringify command in Snap! We won't use lambda in this lab, but you'll see it plenty in 61A.

The map function in Python is actually not used very often. Instead, a closely related construct called a list comprehension is often used instead. An example is given below.


>>> my_list = [1, 2, 3]
                    

>>> [x * x for x in my_list]                          
[1, 4, 9]    
                    

[x * x for x in my_list] may look very strange at first, but once you've used this idea a few times, you'll realize it's quite powerful and easy to use. As before, you'll see that the python code shown is still fairly similar to the Snap! code. The differences are: