Course 2.2Lesson 1 of 5
A list comprehension builds a list in one line: the expression to collect, then for item in iterable, then an optional if that keeps only some items. It is a loop that appends, written short. The if with an else that chooses a value goes before the for. Two for parts make nested loops, with the first as the outer loop, and a comprehension inside a comprehension makes a table or a transposed table. A comprehension is for building a list, one idea at a time. If it needs several conditions and branches, or is used only for its side effects, a plain loop is clearer.
Try the code and the simulations beside the lesson.
After this lesson you can
if, and choose a value with if ... else,You have written this loop many times: make an empty list, loop, and append.
squares = []
for n in numbers:
squares.append(n * n)Python has a short way to write exactly this: a list comprehension.
Predict first. What will each line show? Then run it.
The result is a new list. The long loop and [n * n for n in numbers] give the same list, as the first line of output shows.
A useful way to read one aloud: "the square of n, for each n in numbers, if n is even".
There are two different ifs, and they go in two different places.
if goes at the end: [n for n in numbers if n % 2 == 0] keeps only the even numbers. Items that fail are left out.if ... else goes at the front, as part of the expression: ["even" if n % 2 == 0 else "odd" for n in numbers] gives one value for every item. Nothing is left out.A common mistake is to put else at the end. [n for n in numbers if n > 0 else 0] is a SyntaxError. The choice must come first: [n if n > 0 else 0 for n in numbers].
A comprehension can also hold another comprehension in its expression. [[row * col for col in range(1, 4)] for row in range(1, 4)] makes a table: a list of rows, where each row is itself made by a comprehension. The multiplication table of 3 by 3 is [[1, 2, 3], [2, 4, 6], [3, 6, 9]].
To flatten a table into one list, put the loops in the order that you would write them as nested loops: [item for row in table for item in row].
The last example transposes a matrix: the rows become columns. [[row[i] for row in matrix] for i in range(3)] builds, for each position i, the list of the i-th items of all the rows. The matrix [[1, 2, 3], [4, 5, 6]] becomes [[1, 4], [2, 5], [3, 6]].
Read a comprehension from the middle: for each x in range(n), if the test passes, put x * x in the list.
Rules of thumb.
[print(n) for n in numbers] builds a useless list of None. Use a plain for loop to print.append, but the difference matters only for big lists. Choose for clarity first.else at the end. A SyntaxError. The choice goes at the front.for statements.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
[expression for item in iterable if condition] builds a new list.if goes at the end. A choice if ... else goes at the front.for parts are nested loops, the first one outermost.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
[n * 2 for n in [1, 2, 3] if n > 1]?else go in a comprehension?[x for row in [[1, 2], [3]] for x in row] give?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.