Comprehensions

Comprehensions

Comprehensions in Python let you build lists, sets, and dictionaries with concise and clear syntax. They combine loops and conditional logic into a single expression, making code shorter and easier to maintain. In this guide, we’ll explore the basics of list, set, and dictionary comprehensions, and see how to use them effectively.
Cemil Tokatli
January 21, 2025
Topics:
Share:

Comprehensions are constructs in Python that allow the creation of sequences from other sequences in a concise and expressive way. Python introduced list comprehensions in version 2.0 and later added dictionary comprehensions and set comprehensions in Python 3.0.

List Comprehensions

List comprehensions provide a compact way to transform one list into another by applying a function to each element.

A list comprehension consists of the following components:

  • Input Sequence: The source sequence.
  • Variable: Represents each item in the input sequence.
  • Optional Predicate Expression: A condition to filter elements.
  • Output Expression: Generates items for the resulting list from filtered elements of the input sequence.

article-12.1.png

nums = [2, 4, "4", 3.14, 5]
new = [x * 2 for x in nums if isinstance(x, int)]
print(new) # [4, 8, 10]

a = [1, 2, 3, 4]
b = [i * 2 for i in a]
print(a) #[1, 2, 3, 4]
print(b) #[2, 4, 6, 8]

a = [1, 2, 3, 4, 5, 6, 7, 8]
b = [i * 2 for i in a if i > 5]
print(a) #[1, 2, 3, 4, 5, 6, 7, 8]
print(b) #[12, 14, 16]

x = [x for x in range(0, 10)]
print(x) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

keys = {"a": 1, "b": 2, "c": 3, "d": 4}
x = [f"{a} is {x}" for a, x in keys.items() if x % 2 == 0]
print(x) # ['b is 2', 'd is 4']

Set Comprehensions

Set comprehensions use the same principles as list comprehensions but produce a set as the output.

For example, consider a list of names that may contain duplicates, different capitalization styles, and single-character names. We want only unique names longer than one character, formatted with the first letter capitalized and the rest lowercase.

names = ['Bob', 'JOHN', 'alice', 'bob', 'ALICE', 'J', 'Bob']
new = {name[0].upper() + name[1:].lower() for name in names if len(name) > 1}

print(new) #{'Bob', 'Alice', 'John'}

Dictionary Comprehensions

Dictionary comprehensions are similar to list comprehensions but create a dictionary instead of a list.

a = {x: x for x in range(5)}
print(a) #{0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
k = ["key", "country", "continent"]
c = ["Dublin", "Ireland", "Europe"]

a = {k[x]: c[x] for x in range(len(c))}
print(a) #{'key': 'Dublin', 'country': 'Ireland', 'continent': 'Europe'}

l = {"a": "A", "b": "B"}
x = {key: val for key, val in l.items()}
print(x) #{'a': 'A', 'b': 'B'}