Python List & Dictionary ComprehensionsGet Certified
What Is a Comprehension in Python?
A comprehension is a short way to build a new collection from an existing one. Instead of creating an empty list, writing a for loop, and calling append() on every pass, you describe the whole result in a single line. Many Python programmers find comprehensions easier to read once they are familiar with the pattern.
A comprehension is written inside brackets. The brackets decide which kind of collection you get: square brackets [] make a list, curly braces with key: value make a dictionary, and curly braces with a single expression make a set.
- List comprehension:
[expression for item in iterable]builds a new list. - With a filter:
[expression for item in iterable if condition]keeps only the items that pass the test. - Dictionary comprehension:
{key: value for item in iterable}builds a new dictionary. - Set comprehension:
{expression for item in iterable}builds a set of unique values. - Original is untouched: a comprehension always creates a new collection and leaves the source as it was.
- Readable first: use a comprehension when it makes the code shorter and clearer, not just shorter.
From a for Loop to a List Comprehension
The best way to understand a list comprehension is to compare it with the loop that does the same job. Read it from the middle: for f in temps_f says what to loop over, and the expression at the front says what to put in the new list for each item.
Try It: Convert Fahrenheit to Celsius
Click Test My Code to run the program. Then change the temperatures to your own city’s weather and run it again.
temps_f = [32, 50, 68, 86]
temps_c = []
for f in temps_f:
temps_c.append(round((f - 32) * 5 / 9, 1))
print(temps_c)
temps_c2 = [round((f - 32) * 5 / 9, 1) for f in temps_f]
print(temps_c2)temps_f holds four Fahrenheit temperatures, from the freezing point of water to a hot summer day in Texas.temps_c = [] creates an empty list that the loop will fill.for loop takes the temperatures one at a time and stores each one in f.(f - 32) * 5 / 9 converts to Celsius and round(..., 1) keeps one decimal place. append() adds the result to temps_c.[0.0, 10.0, 20.0, 30.0].f in temps_f, and the results are collected in a new list.[0.0, 10.0, 20.0, 30.0] again, which shows that both versions give the same answer.Filtering with if
Add an if condition at the end of the comprehension to keep only some of the items. Items for which the condition is False are skipped and do not appear in the new list. This replaces the common loop pattern of testing each item before calling append().
Try It: Keep Only the Items You Want
Click Test My Code. Then change the price limit or the starting letter and run it again.
prices = [4.99, 12.50, 7.25, 19.99, 3.00]
under_ten = [p for p in prices if p < 10]
print(under_ten)
names = ["Emily", "Jackson", "Olivia", "Ethan", "Madison"]
e_names = [n for n in names if n.startswith("E")]
print(e_names)prices holds five prices in dollars.p the condition p < 10 is tested. Only prices that pass are copied to the new list. The expression at the front is just p, so the values are not changed.[4.99, 7.25, 3.0]. Python shows 3.00 as 3.0.n.startswith("E") is True only for names that begin with a capital E. The comprehension keeps those names and skips the rest.['Emily', 'Ethan'].Choosing a Value with if/else
An if at the end filters items out. An if ... else at the front does something different: it chooses between two values for every item, so the new list is as long as the original. The form is [value_a if condition else value_b for item in iterable].
Try It: Label Every Score
Click Test My Code. Then change the passing score from 70 to another number.
"Pass" or "Fail" using a passing score of 70, prints the labels, and then counts how many students passed.scores = [92, 78, 65, 88, 54]
results = ["Pass" if s >= 70 else "Fail" for s in scores]
print(results)
print(results.count("Pass"))scores holds five quiz scores.s, Python evaluates s >= 70. If it is True the item is "Pass", otherwise it is "Fail". Every score gets exactly one label.['Pass', 'Pass', 'Fail', 'Pass', 'Fail'].count("Pass") counts how many items equal "Pass", so the output is 3.Transforming Strings
Comprehensions work with any iterable, including lists of strings and even a single string. They are very handy for cleaning text, because you can apply a string method to every item without writing a loop.
Try It: Clean Up a List of Cities
Click Test My Code. Then add your hometown to the list.
cities = ["new york", "los angeles", "chicago", "houston"]
titled = [c.title() for c in cities]
print(titled)
lengths = [len(c) for c in titled]
print(lengths)
initials = [c[0] for c in titled]
print("".join(initials))c.title() capitalizes each word, so the comprehension returns a new list of cleaned names.['New York', 'Los Angeles', 'Chicago', 'Houston'].len(c) counts the characters in each name, including the space.[8, 11, 7, 7].c[0] is the first character of each name, so the comprehension builds the list ['N', 'L', 'C', 'H']."".join(...) glues the letters together with nothing between them. The output is NLCH.Nested Loops in a Comprehension
A comprehension can contain more than one for clause. The clauses are read from left to right, in the same order as nested loops would be written. The first for is the outer loop and the second for is the inner loop. This is useful for combinations, for flattening a list of lists, and for working with tables of data.
Try It: Combinations, Flattening, and Rotating a Table
Click Test My Code. Then add another color or size to see how the number of combinations grows.
colors = ["Red", "Blue"]
sizes = ["S", "M", "L"]
combos = [color + "-" + size for color in colors for size in sizes]
print(combos)
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [n for row in matrix for n in row]
print(flat)
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed)for is the outer loop over colors and the second is the inner loop over sizes. For each color, Python runs through all the sizes and joins the two words with a hyphen.['Red-S', 'Red-M', 'Red-L', 'Blue-S', 'Blue-M', 'Blue-L'], which is 2 × 3 = 6 items.matrix is a list of two rows, and each row is a list of three numbers.for row in matrix takes one row at a time, and the inner for n in row takes each number from that row. The numbers are collected into one flat list.[1, 2, 3, 4, 5, 6].i from every row, which makes one new row. The outer comprehension repeats this for i from 0 to 2.[[1, 4], [2, 5], [3, 6]]. The table now has three rows and two columns.Dictionary Comprehensions
A dictionary comprehension looks like a list comprehension, but it produces a key: value pair for every item. It is perfect for building a lookup table from a list, for swapping the keys and values of an existing dictionary, and for filtering a dictionary. Use items() to loop over the pairs of a dictionary, as you learned in the previous lesson.
Try It: Build, Swap, and Filter a Dictionary
Click Test My Code. Then add another state and its capital city.
states = ["Texas", "Ohio", "Maine", "Florida"]
name_length = {s: len(s) for s in states}
print(name_length)
capitals = {"Texas": "Austin", "Ohio": "Columbus", "Maine": "Augusta"}
by_capital = {cap: st for st, cap in capitals.items()}
print(by_capital)
long_names = {s: n for s, n in name_length.items() if n > 5}
print(long_names)s, the pair s: len(s) is created. The state is the key and the number of letters is the value.{'Texas': 5, 'Ohio': 4, 'Maine': 5, 'Florida': 7}.capitals.items() gives (state, capital) pairs. The comprehension writes them back as capital: state, so the old values become the new keys. This only works well when the values are unique and hashable.{'Austin': 'Texas', 'Columbus': 'Ohio', 'Augusta': 'Maine'}.if n > 5 at the end keeps only the pairs whose value is greater than five. Only 'Florida' has more than five letters.{'Florida': 7}.Using Comprehensions with input()
Comprehensions are a great match for user input. The input() function returns one string, split() breaks it into pieces, and a comprehension converts every piece to a number in one step. Without it you would need a loop and an empty list.
Try It: Basketball Points per Game
The Program Input box is already filled with one line: 21 34 18 27 30. Click Run Code straight away, then try your own numbers separated by spaces.
text = input("Points per game: ")
points = [int(p) for p in text.split()]
high_games = [p for p in points if p >= 25]
print("Points:", points)
print("25+ point games:", high_games)
print("Average:", sum(points) / len(points))input() reads the first line of the Program Input box as a single string, such as "21 34 18 27 30".text.split() breaks the string at the spaces into five small strings. The comprehension converts each one with int(). If any piece is not a whole number, Python stops with a ValueError.high_games.Points: [21, 34, 18, 27, 30].25+ point games: [34, 27, 30].sum() adds the points to get 130, and dividing by len(points), which is 5, gives Average: 26.0.Sets, zip(), and Generator Expressions
The same idea works with other brackets. Curly braces with a single expression build a set comprehension, which removes duplicates automatically. Combined with zip(), which walks through several lists side by side, you can turn two lists into a dictionary. Finally, if you remove the brackets and pass the comprehension straight to a function such as sum(), you get a generator expression. It produces its values one at a time instead of building a whole list in memory.
Try It: GPA Book with zip(), a Set, and a Generator
Click Test My Code. Then change a GPA and watch the honor roll change.
students = ["Liam", "Sophia", "Noah"]
gpas = [3.4, 3.9, 3.1]
gpa_book = {name: gpa for name, gpa in zip(students, gpas)}
print(gpa_book)
honor_roll = [name for name, gpa in gpa_book.items() if gpa >= 3.5]
print(honor_roll)
first_letters = {name[0] for name in students}
print(sorted(first_letters))
total = sum(g for g in gpas)
print(round(total / len(gpas), 2))zip(students, gpas) produces the pairs ("Liam", 3.4), ("Sophia", 3.9), and ("Noah", 3.1). The comprehension unpacks every pair into name and gpa and turns it into a dictionary item.{'Liam': 3.4, 'Sophia': 3.9, 'Noah': 3.1}.gpa >= 3.5.['Sophia'].{name[0] for name in students} collects the first letter of every name. A set keeps each value only once.sorted() turns it into an ordered list. The output is ['L', 'N', 'S'].sum(g for g in gpas) has no square brackets. The values are passed to sum() one at a time, so no extra list is created in memory.3.47.Tip: If a comprehension needs more than two for clauses, or becomes hard to read, switch back to a regular loop. Clear code is better than short code.
Common Mistakes with Comprehensions
- Putting the filter in the wrong place:
[x for x in data if x > 0]filters items out, while[x if x > 0 else 0 for x in data]keeps every item. Writing[x for x in data if x > 0 else 0]causes aSyntaxError. - Forgetting the result: a comprehension that only calls a function, such as
[print(x) for x in data], builds a useless list ofNonevalues. Use a normal loop for side effects. - Reading nested loops backwards: the
forclauses run from left to right, in the same order as the equivalent nested loops. - Confusing
{}types:{x for x in data}is a set,{x: 1 for x in data}is a dictionary, and a bare{}is an empty dictionary. - Losing items in a dictionary: if two items produce the same key, the later one replaces the earlier one, so the dictionary can be shorter than the source.
- Making it too clever: a long comprehension with several conditions is hard to read and hard to debug. Split it into steps.
- Expecting the original to change: a comprehension returns a new collection. Assign the result to a variable, or the new list is lost.
- Reusing a generator: a generator expression can be used only once. After it is exhausted it produces nothing more.
Good Habits for Writing Comprehensions
- Read the comprehension aloud: “give me this for each item in that if condition.”
- Use clear names for the loop variable, such as
priceorstudent, when the meaning is not obvious. - Keep comprehensions short enough to fit comfortably on one line, or break them over several lines.
- Use a regular
forloop when you needbreak,continue, or several statements per item. - Pass a generator expression to
sum(),min(),max(), orany()when you do not need the list itself. - Choose the brackets on purpose:
[]for a list,{k: v}for a dictionary, and{x}for a set.
Key Takeaways
- A comprehension builds a new list, dictionary, or set from an iterable in a single readable expression.
- The pattern is
[expression for item in iterable if condition]. - An
ifat the end filters items. Anif ... elseat the front chooses a value for every item. - Several
forclauses are read from left to right, like nested loops. - A dictionary comprehension uses
key: valueand works well withitems()andzip(). - A set comprehension removes duplicates, and a generator expression saves memory by producing values one at a time.
- Use a comprehension when it makes the code clearer. Otherwise, use a loop.
Frequently Asked Questions
What is a list comprehension in Python?
A list comprehension is a compact way to create a new list from any iterable. It has the form [expression for item in iterable], for example [n * n for n in range(5)]. It replaces the pattern of creating an empty list, looping, and calling append().
How do I add a condition to a list comprehension?
Put an if clause at the end to filter items, as in [n for n in numbers if n > 0]. To choose between two values for every item, put an if-else expression at the front, as in [“Pass” if s >= 70 else “Fail” for s in scores].
What is a dictionary comprehension in Python?
A dictionary comprehension builds a dictionary in one expression using the form {key: value for item in iterable}. For example, {name: len(name) for name in names} creates a dictionary that connects each name to its length.
Are list comprehensions faster than for loops?
A list comprehension is usually a little faster than a loop that calls append(), because Python runs the loop internally. The difference is small for most programs, so the main reason to use a comprehension is readability, not speed.
Can I use nested loops in a list comprehension?
Yes. Write more than one for clause, and Python reads them from left to right as nested loops. For example, [n for row in matrix for n in row] flattens a list of lists into one list.
What is the difference between a list comprehension and a generator expression?
A list comprehension uses square brackets and builds the whole list in memory at once. A generator expression uses parentheses, or no extra brackets when it is the only argument of a function such as sum(), and produces one value at a time. It can be used only once.
How do I create a set comprehension in Python?
Use curly braces with a single expression, such as {word.lower() for word in words}. The result is a set, so duplicate values are removed automatically. Remember that an empty {} is a dictionary, not a set.
When should I not use a comprehension?
Avoid a comprehension when it becomes long or hard to read, when you need break or continue, or when you only want side effects such as printing. In those cases a regular for loop is clearer and easier to debug.