List Comprehensions
List Comprehensions
You should already know what list comprehensions are, but let's quickly recap their syntax
and how they work:
List comprehension:
new_list = [item[::-1] for item in other_list if len(item) > 2]
If the comprehension expression gets too long, it can be split over multiple lines
For example, let's say we want to create a list of squares of all the integers
between 1 and 100 that are not divisible by 2, 3 or 5
sq = [i**2
for i in range(1, 101)
if i%2 and i%3 and i%5]
Nested Comprehensions
And since they are functions, a nested comprehension can access (nonlocal) variables from the
enclosing comprehension!
l = []
for i in range(5):
for j in range(5):
for k in range(5):
l.append((i, j, k))
Note that the order in which the for loops are specified in the comprehension
correspond to the order of the nested loops
Nested Loops in Comprehensions
Again the order of the for and if statements does matter, just like a normal set of for
loops and if statements
won't work!
l = [] l = []
for i in range(5): for i in range(5):
for j in range(5): if i==j:
if i==j: for j in range(5):
l.append((i, j)) l.append((i, j))
j is referenced after
j is created here
it has been created
l = [(i, j) for i in range(5) for j in range(5) if i == j]
won't work!
Nested Loops in Comprehensions
l = []
for i in range(1, 6):
[(i, j)
if i%2 == 0:
for i in range(1, 6) if i%2==0
for j in range(1, 6):
for j in range(1, 6) if j%3==0]
if j%3 == 0:
l.append((i,j))
l = []
[(i, j)
for i in range(1, 6):
for i in range(1, 6)
for j in range(1, 6):
for j in range(1, 6)
if i%2==0:
if i%2==0
if j%3 == 0:
if j%3==0]
l.append((i,j))
l = []
[(i, j)
for i in range(1, 6):
for i in range(1, 6)
for j in range(1, 6):
for j in range(1, 6)
if i%2==0 and j%3==0:
if i%2==0 and j%3==0]
l.append((i,j))
Code
Exercises