A List in One Line
In the lesson on loops, you built a new list from an old one: an empty list before the loop, and .append() inside it. Say a game has a double-points weekend, and every score counts twice:
scores = [12, 7, 15, 9]
doubled = []
for score in scores:
doubled.append(score * 2)
print(doubled)[24, 14, 30, 18]That's three lines just to say “each score, times two”. Building a new list from an old one is so common that Python has a shorter way to write it, the list comprehension:
scores = [12, 7, 15, 9]
doubled = [score * 2 for score in scores]
print(doubled)[24, 14, 30, 18]It's the same loop, written inside square brackets. Read it as “score * 2 for each score in scores”. It has two parts:
- First, what goes into the new list:
score * 2. It's what the loop passed to.append(). - Then the
forpart, the first line of the loop without its colon:for score in scores. It says where the elements come from and what the variable is called.
The square brackets say that the result is a list. Python creates the empty list and appends to it for you. Like the loop, a list comprehension leaves the original list as it was and gives you a new one, so store it in a variable or print it.
Typical mistakes:
- Forgetting the brackets:
doubled = score * 2 for score in scoresends withSyntaxError: invalid syntax. So does a colon at the end,[score * 2 for score in scores:]. A list comprehension has no colon. - Using the list instead of its element:
[scores * 2 for score in scores]. There's no error, but each element of the new list is thenscores * 2, the whole list twice over:
[[12, 7, 15, 9, 12, 7, 15, 9], [12, 7, 15, 9, 12, 7, 15, 9], [12, 7, 15, 9, 12, 7, 15, 9], [12, 7, 15, 9, 12, 7, 15, 9]]In the first part, use the element: score, not scores.
Instructions
- 1
The loop doubles each amount of a pancake recipe for 2 people, so that it's enough for 4. Replace the three lines that build
doubled(the empty list, the loop and.append()) with one line: a list comprehension that stores the same list indoubled. The program still prints[500, 200, 120, 80]. - 2
At the end of the program, make a second list,
tripled, for 6 people: a list comprehension that multiplies each amount ingramsby 3. Print it too:[750, 300, 180, 120]. Keep the line withgramsas it is: the exercise also checks your program with other amounts.