Data Structures · Lists · lesson 5 of 10
List comprehensions
about 14 minutes · free · runs in your browser
Step 1 of 2
Building a list in one line
This shape appears constantly:
squares = []
for n in numbers:
squares.append(n ** 2)
A list comprehension says the same thing in one line:
squares = [n ** 2 for n in numbers]
Read it left to right: what to collect, then where it comes from. You can add a filter on the end:
evens = [n for n in numbers if n % 2 == 0]
And combine the two: [n ** 2 for n in numbers if n > 0].
Comprehensions are idiomatic Python, but they are not free — once one needs two filters and a conditional expression, an ordinary loop is kinder to whoever reads it next.
Your turn: from words, build long_words containing the words longer than four
characters, uppercased. Use a comprehension.
You start from this, and edit it in the browser:
words = ["cat", "python", "dog", "elephant", "ox"]
# Build long_words with a comprehension.
Step 2 of 2
Comprehensions in functions
A comprehension often replaces an entire function body.
Your turn: write clean(values) returning the numbers from values that are
above zero, each rounded to the nearest whole number. Keep the original order.
You start from this, and edit it in the browser:
def clean(values):
# Keep the positives, rounded.
pass