List comprehensions

A concise way to build lists, sets, and dictionaries from other collections.

On this page

Example

#
Python
scores = [45, 82, 67, 91, 30]

passed = [s for s in scores if s >= 60]
curved = [min(s + 10, 100) for s in scores]

print(passed)
print(curved)
Resultsaved result, you can check it
[82, 67, 91]
[55, 92, 77, 100, 40]

Definition and usage

#

A list comprehension builds a new list in a single line: [x * 2 for x in numbers]. It combines a loop with a transformation, and an optional if condition at the end filters the items.

The same syntax works for sets ({…}), dictionaries ({k: v for …}), and generators ((…)). A generator does not build the whole list right away, it supplies items on demand instead, which saves memory.

List comprehensions are readable as long as they stay short. Nested loops and several conditions in one expression are better written out as an ordinary for loop.

Syntax

#
Syntax
[expression for element in collection if condition]

More examples

#
Dictionaries, sets, and generators
Python
names = ["Emma", "Jack", "Mia", "Emma"]

lengths = {name: len(name) for name in names}
unique = {name.lower() for name in names}
total = sum(len(name) for name in names)

print(lengths)
print(sorted(unique))
print(total)
Resultsaved result, you can check it
{'Emma': 4, 'Jack': 4, 'Mia': 3}
['emma', 'jack', 'mia']
15

Good practices

#
  • For sums and checks (sum, any, all), pass a generator expression without square brackets. It does not create an unnecessary list.
  • If the expression does not fit on one readable line, write it out as a loop instead.

Related entries

#

Spotted a mistake or missing an example? Write to us.