Academic Block

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.

What this code does: It converts four temperatures from Fahrenheit to Celsius, first with a regular loop and then with a list comprehension. Both versions print the same list.
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)

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.

What this code does: It filters a list of grocery prices to find the items under ten dollars, and it filters a list of first names to find those that start with the letter E.
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)

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.

What this code does: It labels five quiz scores as "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"))

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.

What this code does: It turns lowercase city names into properly capitalized names, finds the length of each name, and joins the first letter of each city into one short string.
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))

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.

What this code does: It builds every color and size combination for a T-shirt, flattens a table of numbers into a single list, and swaps the rows and columns of the table.
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)

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.

What this code does: It builds a dictionary that connects each state name to its length, swaps a state-to-capital dictionary so that the capitals become the keys, and keeps only the states whose names are longer than five letters.
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)

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.

What this code does: It reads the points a player scored in several games, converts the text to numbers, picks out the games with 25 or more points, and prints the average.
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))

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.

What this code does: It pairs student names with their GPAs in a dictionary, lists the students on the honor roll with a GPA of 3.5 or higher, collects the unique first letters of the names in a set, and calculates the average GPA with a generator expression.
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))
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 a SyntaxError.
  • Forgetting the result: a comprehension that only calls a function, such as [print(x) for x in data], builds a useless list of None values. Use a normal loop for side effects.
  • Reading nested loops backwards: the for clauses 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 price or student, 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 for loop when you need break, continue, or several statements per item.
  • Pass a generator expression to sum(), min(), max(), or any() 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 if at the end filters items. An if ... else at the front chooses a value for every item.
  • Several for clauses are read from left to right, like nested loops.
  • A dictionary comprehension uses key: value and works well with items() and zip().
  • 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.

Ready for the next step?Learn how to pick items from a sequence and put them in order.
Next: Indexing, Slicing & Sorting →