Comprehensions in Python provide a concise, readable, and highly optimized syntax for creating new sequences (lists, dictionaries, sets, and generators) from existing iterables. They eliminate boilerplate accumulator code while offering optimized execution speeds.
1. List Comprehensions Syntax & Mechanics
A list comprehension constructs a new list by applying an expression to each item in an iterable, optionally filtering elements using standard boolean conditions.
2. Dictionary & Set Comprehensions
A. Dictionary Comprehensions
Dictionary comprehensions build dictionaries using key-value pair expressions enclosed within curly braces {}.
B. Set Comprehensions
Set comprehensions create unique, unordered sets while stripping out duplicates automatically during evaluation.
3. Nested Comprehensions & Matrix Operations
Comprehensions can nest multiple for loops to flatten multidimensional structures or construct matrices.
4. Generator Expressions vs. List Comprehensions
Replacing square brackets [] with parentheses () yields a Generator Expression. Instead of building the entire list in memory at once, a generator yields items lazily on demand, drastically reducing memory footprint.
| Feature | List Comprehension [...] |
Generator Expression (...) |
|---|---|---|
| Memory Allocation | Allocates memory for all elements immediately. | Allocates fixed minimal memory regardless of size. |
| Evaluation Strategy | Eager evaluation (computes all results upfront). | Lazy evaluation (computes values one at a time on demand). |
| Reusability | Can be iterated over multiple times; supports indexing. | Exhausts after a single complete iteration pass. |
| Best Use Case | Small-to-medium sequences requiring indexing or re-use. | Large/infinite streams, file processing, memory safety. |
🏋️ Try It Yourself: Practice Challenges
Write a nested list comprehension that transposes a given 2D grid matrix (swapping rows and columns) without using external libraries like NumPy.
Given a dictionary of employee records containing ages and salary levels, construct a dictionary comprehension filtering employees older than 30 with salaries above $70,000.
Construct a set comprehension that extracts all unique consonants from a long paragraph, converting characters to lowercase while stripping spaces, punctuation, and vowels.
Build a list comprehension that yields all prime numbers under 100 by filtering out non-prime values using nested iteration factors.
Design a generator expression combined with conditional transformations to stream and process log strings, yielding structured metadata tuples without loading whole files into memory.
Given a list containing sublists of varying lengths, construct a double-nested list comprehension that flattens all elements into a single flat list while stripping out negative numbers.
Given a list of floating-point test scores, write a list comprehension that converts scores to letter grades: "A" for scores >= 90, "B" for >= 80, "C" for >= 70, and "F" otherwise.
Create a dictionary comprehension that takes a list of strings and maps each string's length to a tuple containing the word and its uppercase version as values.