Comprehensions

SI
Section
Example
Usage Scenarios
Pros
Cons

1

List Comprehension

[x for x in range(5) if x % 2 == 0]

Creating a new list from an existing iterable (e.g., filtering even numbers from a range)

Concise, readable, fast, one-liner solution for filtering & transforming

Can be less readable for complex operations

2

Set Comprehension

{x for x in range(5) if x % 2 == 0}

Removing duplicates from a list, creating a set from an iterable

Eliminates duplicates, fast membership checks, concise

Unordered (can't guarantee order)

3

Dictionary Comprehension

{x: x**2 for x in range(5)}

Creating key-value pairs for a dictionary (e.g., squaring each number)

Concise for generating dictionaries, readable

May be overused for simple key-value pairs

4

Filtering Elements

[x for x in my_list if x > 5]

Filtering elements from an iterable based on a condition (e.g., all elements greater than 5)

Efficient, clear, and elegant syntax for filtering elements

Can lead to nested comprehensions that reduce readability

5

Nested Comprehension

[[x for x in range(3)] for y in range(3)]

Working with multi-dimensional data (e.g., creating a 2D matrix)

Powerful for creating complex structures in one line

Hard to debug, less readable when deeply nested

Last updated