Python Comprehension

Comprehensions in Python provide a concise way to create collections, such as lists, dictionaries, and sets, by embedding expressions within brackets. They allow for looping, filtering, and processing data in a readable, one-liner format, significantly reducing the amount of code needed for creating or transforming data structures. Python comprehensions come in four main forms:

  1. List Comprehension
  2. Dictionary Comprehension
  3. Set Comprehension
  4. Generator Comprehension

1. List Comprehensions

List comprehension creates a new list by iterating over a sequence and applying an expression. Its syntax is as follows:
[expression for item in iterable if condition]
This example generates a list of squares for numbers from 1 to 5.
squares = [x ** 2 for x in range(1, 6)]
print("Squares:", squares)

Output:
Squares: [1, 4, 9, 16, 25]

Explanation: The expression `x ** 2` squares each element `x`, iterating through `range(1, 6)`, resulting in `[1, 4, 9, 16, 25]`.

2. Adding Conditions to List Comprehensions

Conditions can be added to filter items in the iterable. Here, we generate a list of even numbers.
evens = [x for x in range(10) if x % 2 == 0]
print("Even numbers:", evens)

Output:
Even numbers: [0, 2, 4, 6, 8]

Explanation: Only numbers satisfying `x % 2 == 0` are added to `evens`, creating a list of even numbers from `0` to `9`.

3. Nested Loops in List Comprehensions

List comprehensions can have nested loops, allowing combinations of elements. Here, we generate pairs of coordinates:
coordinates = [(x, y) for x in range(3) for y in range(2)]
print("Coordinates:", coordinates)

Output:
Coordinates: [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]

Explanation: Each `x` in `range(3)` pairs with each `y` in `range(2)`, generating all coordinate pairs in the output.

4. Dictionary Comprehensions

Dictionary comprehension allows creating dictionaries in a compact way with the following syntax:
{key_expression: value_expression for item in iterable if condition}
For example, creating a dictionary mapping numbers to their squares:
squares_dict = {x: x ** 2 for x in range(1, 6)}
print("Squares Dictionary:", squares_dict)

Output:
Squares Dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Explanation: For each `x` in `range(1, 6)`, `x` becomes the key and `x ** 2` the value.

5. Adding Conditions in Dictionary Comprehensions

We can add a condition to include only specific items in the dictionary. Here, we map even numbers to their squares:
even_squares_dict = {x: x ** 2 for x in range(10) if x % 2 == 0}
print("Even Squares Dictionary:", even_squares_dict)

Output:
Even Squares Dictionary: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Explanation: The condition `x % 2 == 0` filters for even numbers, mapping them to their squares.

6. Set Comprehensions

Set comprehension is similar to list comprehension but creates a set, ensuring unique elements in the output:
unique_squares = {x ** 2 for x in range(-5, 6)}
print("Unique Squares:", unique_squares)

Output:
Unique Squares: {0, 1, 4, 9, 16, 25}

Explanation: The output set has unique squares from numbers in `range(-5, 6)`, removing duplicate values.

7. Generator Comprehensions

Generator comprehensions are similar to list comprehensions but use parentheses instead of brackets and return a generator object. This approach is memory efficient for large data, as it generates items one at a time.
squared_gen = (x ** 2 for x in range(1, 6))

# Convert generator to list for display
print("Generator squares:", list(squared_gen))

Output:
Generator squares: [1, 4, 9, 16, 25]

Explanation: `squared_gen` is a generator that yields squares from `range(1, 6)`. Converting to a list shows the full sequence.

8. Nested Comprehensions

Comprehensions can be nested to create complex structures. Here, we create a 2D matrix (list of lists):
matrix = [[x * y for y in range(1, 4)] for x in range(1, 4)]
print("2D Matrix:", matrix)

Output:
2D Matrix: [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

Explanation: Each inner list contains multiples of `x` for values in `range(1, 4)`, resulting in a matrix-like structure.

9. Complex Example: Transpose of a Matrix

Using list comprehension, we can transpose a 2D matrix:
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Transposing the matrix
transpose = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print("Transposed Matrix:", transpose)

Output:
Transposed Matrix: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Explanation: This list comprehension iterates over columns by row, producing a transposed version of the matrix.

10. Dictionary of Lists Using Comprehension

We can create a dictionary with keys and values as lists through comprehension:
names = ["Alice", "Bob", "Cathy"]
ages = [24, 30, 27]
name_age_dict = {name: age for name, age in zip(names, ages)}
print("Name-Age Dictionary:", name_age_dict)

Output:
Name-Age Dictionary: {'Alice': 24, 'Bob': 30, 'Cathy': 27}

Explanation: Using `zip`, we pair each name with an age, creating a dictionary from the paired values.

11. Practical Use Case: Word Lengths Dictionary

Let's create a dictionary mapping words to their lengths:
words = ["apple", "banana", "cherry"]
length_dict = {word: len(word) for word in words}
print("Word Lengths Dictionary:", length_dict)

Output:
Word Lengths Dictionary: {'apple': 5, 'banana': 6, 'cherry': 6}

Explanation: `len(word)` computes the length for each word, storing the result in a dictionary.

Summary

Python comprehensions offer powerful, readable, and memory-efficient ways to create collections. From basic lists and dictionaries to nested and conditional comprehensions, they reduce code complexity and make logic more compact and readable.

Previous: Python Queue | Next: Python namedtuple

<
>