python comprehension lists dictionaries

Comprehensions in Python

Learning objectives

By the end of this pill you will be able to:

  • understand the comprehension syntax in Python;
  • create lists, sets and dictionaries in a compact and elegant way;
  • apply conditions (if) and nested loops inside comprehensions;
  • distinguish between the various comprehension types (list, set, dict, generator).

What is a comprehension

A comprehension is a concise way to build collections from iterables (lists, ranges, strings, etc.) using the syntax:

[expression for element in iterable if condition]

Comprehensions exist for:

  • Lists → [ ... ]
  • Sets → { ... }
  • Dictionaries → { key: value for ... }
  • Generator expressions → ( ... )

List comprehension

Basic example

numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)   # [1, 4, 9, 16, 25]

With a condition

evens = [x for x in range(10) if x % 2 == 0]
print(evens)   # [0, 2, 4, 6, 8]

With a conditional expression

label = ["even" if x % 2 == 0 else "odd" for x in range(5)]
print(label)  # ['even', 'odd', 'even', 'odd', 'even']

With nested loops

products = [(x, y) for x in [1,2,3] for y in [10,20]]
print(products)   # [(1,10), (1,20), (2,10), (2,20), (3,10), (3,20)]

Set comprehension

Like list comprehensions but using curly braces. Duplicates are automatically eliminated.

word = "programming"
unique_chars = {c for c in word}
print(unique_chars)   # random order, e.g. {'p','r','o','g','a','m','i','n'}
squares = {x**2 for x in range(6)}
print(squares)   # {0, 1, 4, 9, 16, 25}

Dict comprehension

Allows you to build dictionaries in one line.

numbers = [1, 2, 3, 4]
d = {x: x**2 for x in numbers}
print(d)   # {1:1, 2:4, 3:9, 4:16}
text = "banana"
count = {c: text.count(c) for c in set(text)}
print(count)   # {'b':1, 'a':3, 'n':2}

Generator expression

Like list comprehensions but with round parentheses: values are produced “on the fly” without creating the entire list in memory.

gen = (x**2 for x in range(5))
print(next(gen))   # 0
print(next(gen))   # 1
print(list(gen))   # [4, 9, 16]

Practical examples

Filtering prime numbers (simplified)

numbers = range(2, 20)
primes = [x for x in numbers if all(x % d != 0 for d in range(2, x))]
print(primes)   # [2, 3, 5, 7, 11, 13, 17, 19]

Transforming strings

names = ["luca", "maria", "giovanni"]
upper = [n.upper() for n in names]
print(upper)   # ['LUCA', 'MARIA', 'GIOVANNI']

Flattening a matrix

matrix = [[1,2],[3,4],[5,6]]
flat = [x for row in matrix for x in row]
print(flat)   # [1, 2, 3, 4, 5, 6]

Reversing a dictionary

subjects = {"ita":7, "mat":8, "cs":9}
reversed_d = {v:k for k,v in subjects.items()}
print(reversed_d)   # {7:'ita', 8:'mat', 9:'cs'}

Final comparison

  • List comprehension: produces a list (ordered, duplicates allowed).
  • Set comprehension: produces a set (unordered, no duplicates).
  • Dict comprehension: produces a dictionary (key:value).
  • Generator expression: produces values one at a time; useful with large data.

In brief: comprehensions make code more compact and readable. Experiment with conditions and nested loops to create powerful transformations in just a few lines!