A comprehension builds a collection while it loops.
A regular for loop is often the clearest place to start. When the loop has one focused job—build a collection—a comprehension can express the same idea in one readable line.
numbers = [1, 2, 3, 4]
squares = []
for number in numbers:
squares.append(number * number)
# The same focused transformation:
squares = [number * number for number in numbers]Both versions visit each number and add its square to a new list. The comprehension keeps the result expression, the loop variable, and the source data together.
print(squares) # [1, 4, 9, 16]The brackets choose the result type: [] makes a list, {} with one expression makes a set, and {key: value} makes a dictionary.
Keep readability first: Use a regular loop when the work needs several steps, multiple side effects, or a long nested condition. A short comprehension should make code easier—not harder—to read.
names = ["ana", "marko", "jelena"]
uppercase_names = [name.upper() for name in names]
words = ["Python", "practice", "Python"]
initials = {word[0].lower() for word in words}
scores = {"Ana": 82, "Marko": 45, "Jelena": 91}
passed_scores = {name: score for name, score in scores.items() if score >= 60}The first line transforms every name into a list. The second keeps unique initials in a set. The last one keeps only passing name-and-score pairs in a dictionary.
prices = [100, 250, 80]
with_tax = [price * 1.2 for price in prices]The expression before for is the value added for each price.
cities = ["Novi Sad", "Niš", "Novi Sad"]
lengths = {len(city) for city in cities}A set removes duplicate results. Do not use it when the displayed order matters.
words = ["python", "code"]
word_lengths = {word: len(word) for word in words}Put the key and value before for. Repeated keys replace an earlier value, so choose keys carefully.
Read a comprehension from right to left
- 1. Start with the source
for name, score in scores.items()supplies one name-and-score pair at a time. - 2. Choose the result expression
name,score * 1.2, orname: scoredescribes what one iteration contributes. - 3. Add an optional filter
if score >= 60keeps only iterations that meet the condition; it does not run anelsebranch. - 4. Check the outer bracketsSquare brackets create a list, curly brackets create a set, and
key: valueinside curly brackets creates a dictionary.
Common mistakes
- Choosing the wrong collectionUse a list for ordered results, a set for unique values, and a dictionary when each value needs a meaningful key.
- Expecting a set orderSets are useful for uniqueness, not for a predictable display order.
- Accidentally repeating a dictionary keyA later value for the same key replaces an earlier one.
- Hiding too much work in one lineIf you need to explain the line several times, prefer a regular loop with named intermediate values.
