Python lesson 24

List Comprehensions. A List in One Line

The shortcut every Python programmer uses.

The Same Loop, Squashed

Four lines of loop become one line inside square brackets. Read it out loud in order: the thing you want, then for each item, then the list it comes from. You can add an if on the end to keep only some of them.

# the long way
doubles = []
for n in numbers:
doubles.append(n * 2)

# the same thing
doubles = [n * 2 for n in numbers]

# only the big ones
big = [n for n in numbers if n > 10]

numbers = [1, 2, 3, 4, 5]
doubles = [n * 2 for n in numbers]
print(doubles)

Read It Out Loud

numbers = [1, 2, 3, 4]
result = [n * n for n in numbers]
print(result)

Keep Only the Big Ones

Rebuild It the Long Way

Shout Every Name

Build a new list with every name in capitals, in one line.

names = ["nova", "blaze", "echo"]
shouted = [name.upper() for name in names]
print(shouted)

Even Squares Only

From 1 to 10, square each number but keep only the even results.

result = [n * n for n in range(1, 11) if (n * n) % 2 == 0]
print(result)

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.