A very common loop makes a new list from an old one: go through each item, maybe skip some, change the rest, append. Python has a short way to write that, the list comprehension.
nums = [1, 2, 3, 4, 5]
squares = []
for n in nums:
squares.append(n * n)
print(squares)
print([n * n for n in nums])
Prints
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
Read it as "n times n, for each n in nums". The part before for is what goes in the new list. Add if at the end to keep only some items:
nums = [5, 12, 7, 20, 3]
print([n for n in nums if n > 6])
print([w.upper() for w in ["hi", "yo"]])
Prints
[12, 7, 20]
['HI', 'YO']
The same idea makes dicts and sets: {key: value for ...} and {value for ...}.
words = ["duck", "goose", "swan"]
lengths = {w: len(w) for w in words}
print(lengths)
Prints
{'duck': 4, 'goose': 5, 'swan': 4}
Keep comprehensions short. If one needs two lines or several conditions, a normal loop is easier to read, and readability matters more than saving lines.
enumerate() gives you each item together with its position, so you don't need a separate counter. It starts at 0 unless you tell it otherwise.
podium = ["Ana", "Ben", "Cy"]
for place, name in enumerate(podium, start=1):
print(place, name)
Prints
1 Ana
2 Ben
3 Cy
zip() walks through two (or more) lists side by side, giving one item from each at a time. It stops at the end of the shortest. dict(zip(keys, values)) builds a dictionary from two lists.
names = ["Ana", "Ben"]
scores = [88, 92]
for n, s in zip(names, scores):
print(f"{n}: {s}")
print(dict(zip(names, scores)))
Prints
Ana: 88
Ben: 92
{'Ana': 88, 'Ben': 92}
any() and all() pair well with these: any(x > 100 for x in prices) is True if at least one is over 100, all(...) only if every one is.
Practice
What does this print?
print([n * 10 for n in range(4)])
More info
Quick reference
[expr for x in items if cond]
A list comprehension: transform and filter in one line.