6 Comprehensions

Introduction

  • Comprehensions in Python are a concise and powerful way to create new sequences (like lists, sets, or dictionaries) from existing iterables.
  • They are shorter, more readable, and often faster than using loops.
  • Types of comprehensions:
    1. List Comprehensions
    2. Set Comprehensions
    3. Dictionary Comprehensions
    4. Generator Expressions

List Comprehensions

  • Syntax:
[expression for item in iterable if condition]
  • Example:
# Squares of numbers from 1 to 5
squares = [x**2 for x in range(1, 6)]
print(squares)
[1, 4, 9, 16, 25]
  • Equivalent using loops:
squares = []
for x in range(1, 6):
    squares.append(x**2)
print(squares)
[1, 4, 9, 16, 25]

Adding Conditions

  • We can add an if condition inside a comprehension.
# Even numbers from 1 to 10
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)
[2, 4, 6, 8, 10]

Nested Comprehensions

  • Comprehensions can be nested for multiple loops.
# Multiplication table (pairs)
pairs = [(x, y) for x in range(1, 4) for y in range(1, 4)]
print(pairs)
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

Set Comprehensions

  • Similar to list comprehensions but use {}.
# Unique letters in a word
letters = {ch for ch in "engineering"}
print(letters)
{'r', 'e', 'g', 'n', 'i'}

Dictionary Comprehensions

  • Syntax:
{key_expression: value_expression for item in iterable if condition}
  • Example:
# Squares dictionary
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Generator Expressions

  • Use () instead of [].
  • They produce values lazily (one at a time).
# Generator for squares
squares_gen = (x**2 for x in range(1, 6))
print(next(squares_gen))  # 1
print(next(squares_gen))  # 4
1
4

Advantages of Comprehensions

  • Concise: Write less code.
  • Readable: Easier to understand than loops (in many cases).
  • Efficient: Faster execution in most scenarios.

Exercises

  1. Create a list comprehension to find all numbers divisible by 3 between 1 and 30.
  2. Use a set comprehension to find unique vowels in the string "statistics".
  3. Write a dictionary comprehension to map numbers 1–10 to their cubes.
  4. Use a generator expression to generate factorial values of 1–6.