Comprehensions in Python

Comprehensions in Python provide a concise and elegant way to create new sequences (like lists, sets, or dictionaries) from existing iterables such as lists, tuples, or ranges.

They replace lengthy loops with single-line expressions โ€” improving both readability and performance.

What are Comprehensions?

Comprehensions allow you to construct new collections using a compact syntax.

General Syntax:

new_collection = [expression for item in iterable if condition]
expression โ€” what to do with each item
iterable โ€” the source sequence
condition โ€” (optional) filter to include specific elements

List Comprehensions

List comprehensions create new lists in a single line.

Example โ€“ Squares of numbers:

squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]
Example โ€“ Filtering even numbers:

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

evens = []
for x in range(10):
    if x % 2 == 0:
        evens.append(x)
As you can see, list comprehensions are shorter and more expressive.

Dictionary Comprehensions

Dictionary comprehensions allow you to build dictionaries dynamically.

Example โ€“ Creating a dictionary of squares:

squares = {x: x**2 for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Example โ€“ Filtering dictionary items:

students = {"Alice": 85, "Bob": 65, "Charlie": 90, "David": 70}
passed = {k: v for k, v in students.items() if v >= 75}
print(passed)  # {'Alice': 85, 'Charlie': 90}

Set Comprehensions

Set comprehensions work like list comprehensions but create sets (unordered collections with unique elements).

Example โ€“ Unique squares:

nums = [1, 2, 2, 3, 3, 4]
unique_squares = {x**2 for x in nums}
print(unique_squares)  # {16, 1, 4, 9}

Conditional Comprehensions

You can include if and else conditions in comprehensions for more control.

Example โ€“ Conditional expression:

results = ["Even" if x % 2 == 0 else "Odd" for x in range(6)]
print(results)  # ['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']
Example โ€“ Nested condition:

numbers = [x for x in range(20) if x % 2 == 0 if x % 3 == 0]
print(numbers)  # [0, 6, 12, 18]

Nested Comprehensions

You can also use comprehensions inside another comprehension (though readability should be considered).

Example โ€“ Multiplication table:

table = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(table)
# [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

Summary

Comprehensions make your Python code more elegant, faster, and readable. They are not just syntax sugar โ€” they're a functional and efficient alternative to traditional loops.

Concept Description
List Comprehension [expr for item in iterable if condition]
Dict Comprehension {key: value for item in iterable}
Set Comprehension {expr for item in iterable}
Conditional Comprehension Adds filtering or inline if-else logic
Nested Comprehension Comprehensions within comprehensions
Mastering list, dict, and set comprehensions will elevate your Python programming style, especially in data manipulation, filtering, and transformation tasks.

In the next article, we'll explore Iterators and Generators in Python โ€” understanding lazy evaluation and memory-efficient data handling.
Share this Article