← Python from Scratch
Lesson 37 of 78 · 10 XP
Looping over lists and list comprehensions
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
You can go through a list with an ordinary for. If you also need each item's number, use enumerate:
for i, name in enumerate(["Anya", "Borya"], start=1):
print(i, name) # 1 Anya, 2 Borya
Very often you build one list from another. You can do it like this:
squares = []
for n in [1, 2, 3]:
squares.append(n * n)
Or more briefly — with a list comprehension:
squares = [n * n for n in [1, 2, 3]] # [1, 4, 9]
evens = [n for n in range(10) if n % 2 == 0] # [0, 2, 4, 6, 8]
words = [w.upper() for w in ["a", "b"]] # ['A', 'B']
It reads almost like a sentence: "n * n for each n in the list, if the condition holds". You don't have to use comprehensions, but in real Python code you'll see them all the time.
Task. Write a function squares_of_even(nums) that returns a list of the squares of only the even numbers, in their original order. squares_of_even([1, 2, 3, 4]) → [4, 16].
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.