List, Dict, & Set Comprehensions
Overview
Comprehensions provide a concise way to create lists, dictionaries, and sets from existing collections.
Learning Objectives
- Create filtered lists using list comprehensions.
- Build key-value mappings using dictionary comprehensions.
- Create deduplicated sets using set comprehensions.
Concept Explanation
Comprehensions are concise inline loops. The basic syntax is: [expression for item in collection if condition]. They run slightly faster than manual loop appends and are highly readable when kept simple.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
squares = [x * x for x in range(5)]
print(squares)
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
prices = [12.0, -1.5, 30.0, -5.0, 15.0]
# Filter positive prices only
valid_prices = [p for p in prices if p > 0]
print(valid_prices)
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
# Dictionary comprehension mapping raw tuples list to cleaned values
raw_data = [('user1', 'admin'), ('user2', 'guest')]
user_directory = {user_id.upper(): role.lower() for user_id, role in raw_data if role != 'guest'}
print(user_directory)
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Loop collection elements → Run condition check → If True, evaluate expression → Accumulate in new list
Common Mistakes
Review these common pitfalls when working with this topic:
- Writing nested or multi-loop comprehensions that are hard to read.
- Using list comprehensions for side-effects like print statements instead of generating values.
- Writing a tuple comprehension using parentheses (this actually returns a lazy generator object).
- Executing slow calculations inside comprehension condition checks.
Best Practices
Enforce these Pythonic best practices in your codebase:
squares = []
for x in range(5):
squares.append(x * x) # Verbose loop append
squares = [x * x for x in range(5)] # Clean comprehension
Performance Notes
Keep these optimization guidelines in mind for performance-sensitive hotpaths:
- Comprehensions execute faster than manual append loops because they avoid calling the .append attribute at the bytecode level.
Quick Revision
Use these key summaries for last-minute revision:
- Comprehensions provide a concise way to construct collections.
- Syntax: [expr for item in iter if cond].
- Supports lists, sets, and dictionary types.
- Runs slightly faster than standard loops.
- Keep comprehensions on a single line for readability.
- Parentheses create lazy generator expressions.