Comprehensions in Python

Module 2 • Session 19 • Comprehensive Guide

list-comprehension dict-comprehension set-comprehension generator-expressions nested-loops

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.

# Generic Syntax: # [expression for item in iterable if condition] # Basic Example: Squares of even numbers numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_squares = [x**2 for x in numbers if x % 2 == 0] print("Even Squares:", even_squares) # [4, 16, 36, 64, 100] # Conditional Expression (If-Else in output transformation) # [expr_if_true if condition else expr_if_false for item in iterable] labels = ["Even" if x % 2 == 0 else "Odd" for x in numbers] print("Labels:", labels)

2. Dictionary & Set Comprehensions

A. Dictionary Comprehensions

Dictionary comprehensions build dictionaries using key-value pair expressions enclosed within curly braces {}.

# Syntax: {key_expr: value_expr for item in iterable if condition} # Creating a word-length map words = ["python", "comprehension", "code", "expressive", "list"] word_length_map = {word: len(word) for word in words if len(word) > 4} print("Word Length Map:", word_length_map) # Swapping keys and values in a dictionary original_dict = {"a": 1, "b": 2, "c": 3} inverted_dict = {value: key for key, value in original_dict.items()} print("Inverted Dict:", inverted_dict)

B. Set Comprehensions

Set comprehensions create unique, unordered sets while stripping out duplicates automatically during evaluation.

# Syntax: {expression for item in iterable if condition} raw_data = ["apple", "banana", "APPLE", "Cherry", "BANANA", "date"] unique_words = {word.lower() for word in raw_data} print("Unique Lowercase Words:", unique_words) # {'apple', 'banana', 'cherry', 'date'}

3. Nested Comprehensions & Matrix Operations

Comprehensions can nest multiple for loops to flatten multidimensional structures or construct matrices.

# Matrix Flattening matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] flattened = [num for row in matrix for num in row] print("Flattened Matrix:", flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9] # 3x3 Identity Matrix Construction identity_matrix = [[1 if row == col else 0 for col in range(3)] for row in range(3)] print("Identity Matrix:", identity_matrix)

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.
import sys # Memory usage comparison example large_range = range(1_000_000) list_comp = [x * 2 for x in large_range] gen_exp = (x * 2 for x in large_range) print("List Comprehension Memory (bytes):", sys.getsizeof(list_comp)) # ~8 MB print("Generator Expression Memory (bytes):", sys.getsizeof(gen_exp)) # ~200 Bytes

🏋️ Try It Yourself: Practice Challenges

Challenge 1: Matrix Transposition Pipeline

Write a nested list comprehension that transposes a given 2D grid matrix (swapping rows and columns) without using external libraries like NumPy.

Challenge 2: Multi-Criteria Dictionary Filter

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.

Challenge 3: Vowel-Stripped Set Generator

Construct a set comprehension that extracts all unique consonants from a long paragraph, converting characters to lowercase while stripping spaces, punctuation, and vowels.

Challenge 4: Prime Number Sieve via Comprehension

Build a list comprehension that yields all prime numbers under 100 by filtering out non-prime values using nested iteration factors.

Challenge 5: Lazy File Line Processor

Design a generator expression combined with conditional transformations to stream and process log strings, yielding structured metadata tuples without loading whole files into memory.

Challenge 6: Flattening Complex Nested Lists

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.

Challenge 7: Conditional Value Formatting

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.

Challenge 8: Inverted & Grouped Key Mapping

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.

⚡ Interactive Sandbox (Comprehensions in Python (List, Dict, Set & Generator Expressions))
Console Output:
Click "Run Code" above to execute interactive scripts...

📝 Knowledge Check Quiz

1. What is the main memory advantage of Generator Expressions `(...)` over List Comprehensions `[...]`?
2. Which syntax correctly includes an `if-else` conditional assignment in a list comprehension output?
3. What will be the output of `{x % 3 for x in range(10)}`?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)