Replace your building loops with expressive comprehensions, to transform, filter and reindex your data.
Open this lesson in KodokonA list comprehension condenses the most common pattern in programming: building a list by transforming or filtering a sequence. The syntax reads like a sentence: [expression for element in sequence if condition]. Same result as a loop with append, in a single declarative line that every Python developer recognizes instantly.
prices = [12.0, 49.9, 5.5, 199.0]
with_tax = [round(p * 1.2, 2) for p in prices]
cheap = [p for p in prices if p < 50]
print(with_tax) # [14.4, 59.88, 6.6, 238.8]
print(cheap) # [12.0, 49.9, 5.5]The dictionary comprehension follows the same logic with the {key: value for ...} syntax. A very common use case in projects: reindexing a list of objects by their identifier, to then get instant lookups instead of scanning the list every time you need something.
users = [
{"id": 7, "name": "Alice"},
{"id": 12, "name": "Bruno"},
{"id": 31, "name": "Chloe"},
]
by_id = {u["id"]: u["name"] for u in users}
print(by_id[12]) # Bruno
print(31 in by_id) # TrueTwo positions for if, two different roles. Placed after the for, it filters: rejected elements don't appear in the result. Placed before the for, as a conditional expression (a if condition else b), it chooses a value for each element: the list then keeps the same length as the source.
scores = [45, 82, 67, 91]
labels = ["pass" if s >= 60 else "fail" for s in scores]
print(labels) # ['fail', 'pass', 'pass', 'pass']