Python Comprehensions

List Comprehensions

One of the most important (but tricky) Python concepts is the list comprehension, which can act almost indistinguishably from the map and keep HoFs.

Map in Python

First, let's discuss how list comprehensions can be used to emulate the map HoF. 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. While a bit alien, we can see that Python code using comprehensions is still somewhat similar to the Snap! code. The differences are:

Despite these syntactic differences, the net result is exactly the same: We multiply each element of my_list by itself, producing the effect of squaring each number. And like the map block in Snap!, we produce a new list without changing the original list.

The syntax for a list comprehension is as follows:


>>> [function(x) for x in my_list]
        

This syntax can be confusing at first because it looks like we're writing a for loop on one line inside of a list. Don't be fooled! This isn't actually a for loop at all, but instead special syntax that cosmetically resembles a for loop. Again, list comprehensions look weird, but they'll make more sense once you start using them.

Keep in Python

List comprehensions are used to do keep as well. An example of using a comprehension to keep items is shown below.


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

>>> [x for x in my_list if x < 3]
[1, 1, 2]
                    

More generally, if we want to keep only items corresponding to some predicate, we'd use the following. Keep in mind that a predicate is simply a function that returns True or False.


>>> [x for x in my_list if predicate(x)]
        

Using List Comprehensions for Map and Keep Simultaneously

List comprehensions can be used to perform map and keep at the same time. We've also seen how to do this in Snap!, as shown to the right. Observe that the list comprehension is more concise.


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

>>> [x + 5 for x in my_list if x <  3]
[6, 6, 7]
                    

Exercise 3.1: Squares of Evens

Write the function squares_of_evens that takes as input a list of numbers, and returns a list that is equal to the squares of all even numbers. Use list comprehensions.


>>> squares_of_evens([-5, -2, 0, 1, 3, 4, 8])
[4, 0, 16, 64]
        

Exercise 3.2: Nth Power of Evens

Write the function nth_power_of_evens that takes as input an integer n as well as a list of numbers, and returns a list that is equal to the nth power of all even numbers in the list. As before, use list comprehensions.


>>> nth_power_of_evens([-5, -2, 0, 1, 3, 4, 8], 3)
[-8, 0, 64, 512]
        

To test these functions, run:


python3 -m doctest lab2starter.py
        

backnext