Comprehensions instead of loops
Many loops you've written follow the same recipe: start with an empty list, go through a series, maybe check a condition, and append one value per round. Every loop like that can become a comprehension. Each part of the loop has its place:
long_names = []
for name in names:
if len(name) > 4:
long_names.append(name.upper())
long_names = [name.upper() for name in names if len(name) > 4]
What was appended moves to the front, the for line stays in the middle, and the if goes to the end.
Your own functions inside
When the expression needs several lines of work, write a function for it and call the function in the comprehension:
def grade(points):
if points >= 90:
return "A"
if points >= 75:
return "B"
return "C"
points = [95, 80, 62, 77]
print([grade(p) for p in points])
['A', 'B', 'C', 'B']The comprehension stays short and readable, and the function can be tested on its own.
Lists, tuples and objects as items
The items can be anything, and so can the values you make from them. Here the items are lists and the new items are tuples:
>>> table = [[3, 8, 1], [5], [9, 2]]
>>> [len(row) for row in table]
[3, 1, 2]
>>> [max(row) for row in table]
[8, 5, 9]
>>> [(n, n * n) for n in range(1, 4)]
[(1, 1), (2, 4), (3, 9)]Items that are objects work the same way: [book.title for book in books] makes a list of the books' titles.
Two lists side by side
To combine two lists of the same length item by item, go through the indexes with range(len(...)):
prices = [3, 10, 2]
amounts = [4, 1, 5]
totals = [prices[i] * amounts[i] for i in range(len(prices))]
print(totals)
[12, 10, 10]Counting and adding up
A comprehension makes a list, and the functions you know for lists work on it right away. len of a filtered list counts the items that pass, and sum adds the values up:
>>> scores = [72, 45, 90, 38, 66]
>>> len([s for s in scores if s >= 50])
3
>>> sum([s for s in scores if s >= 50])
228When to keep the loop
A comprehension is for building a list. When a loop does something else, such as printing, asking for input or updating several variables at once, keep the loop. And if a comprehension grows so long that you have to read it three times, a loop or a helper function is kinder to the next reader.