List comprehension#
List and dictionary comprehensions are elegant constructs in Python that allow you to manipulate Python objects in a very compact and efficient way. You can think of them as writing a for
loop in a single line. Here is the syntax:
[<DO_SOMETHING> for <ITEM> in <ITERABLE>]
Note the following key elements:
the list comprehension is enclosed in list brackets:
[ ... ]
<DO_SOMETHING>
is any Python expression (for example,print()
orx**2
)<ITEM>
is generally a (temporary) variable that is used in the expression<DO_SOMETHING>
and represents all of the “items” in<ITERABLE>
<ITERABLE>
is an iterable object, a collection of “items”. Don’t worry about what this is exactly (we will study it more later).
For our purposes, it is enough to consider the following iterables:
lists (e.g.,
[1, 2, 3]
)ndarrays (Numpy)
range()
dictionaries
As with assert statements, the best way to illustrate this is by example.
\(\text{Task 6.1:}\)
Read the cell below then execute it to see an example of a “normal” for loop that creates a list of squares from 0 to 9.
squares = []
for i in range(10):
squares.append(i**2)
print(squares)
\(\text{Task 6.2:}\)
Read the cell below then execute it to see an example of a list comprehension that does the same thing. It’s much more compact, right?!
squares = [i ** 2 for i in range(10)]
print(squares)
\(\text{Task 6.3:}\)
Read the cell below then execute it to see an example of a “normal” for loop that creates a dictionary that maps numbers to their squares.
squares_dict = {}
for i in range(10):
squares_dict[i] = i ** 2
print(squares_dict)
\(\text{Task 6.4:}\)
Read the cell below then execute it to see an example of a list comprehension that does the same thing. Again much more compact!
squares_dict = {i: i ** 2 for i in range(10)}
print(squares_dict)
\(\text{Task 6.5:}\)
Now try it yourself! Create a new list new_list
from the one defined below that has values that are half that of the original my_list
.
Note the use of asserts to make sure your answer is correct!
my_list = [1, 2, 3, 4, 5]
new_list = [# YOUR_CODE_LINE_HERE]
print(new_list)
Summary#
There are several reasons why you should use list comprehension, hopefully you can recognize them from the examples and tasks above:
Readability: Comprehensions often turn multiple lines of code into a single, readable line, making the code easier to understand at a glance.
Efficiency: They are generally faster because they are optimized in the Python interpreter.
Simplicity: Reduces the need for loop control variables and indexing, making the code simpler.
Sometimes the hardest thing to remember is the order and syntax. The following list comprehension uses obvious variable names to illustrate it (assuming you have an object with “stuff” in it, for example, objects = [1, 2, 3]
); if you can remember this, you can remember list comprehensions!
[print(object) for object in objects]
By Tom van Woudenberg and Robert Lanzafame, Delft University of Technology. CC BY 4.0, more info on the Credits page of Workbook.