Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / Python Tutorial / Chapter 3: Data Structures & Collections
PYTHON ⏱ 10 min read

List and Dictionary Comprehensions

Comprehensions are one of Python's most celebrated features, offering an elegant one-line syntax to create new lists or dictionaries.

What is it?

A comprehension provides a concise way to create lists, dictionaries, or sets based on existing iterables.

Why is it used?

Replaces multi-line loops and `.append()` calls with clear, expressive, and faster one-liners.

Detailed Explanation

Syntax Formulas: • List Comprehension: `[expression for item in iterable if condition]` • Dictionary Comprehension: `{key_expr: val_expr for item in iterable if condition}` • Set Comprehension: `{expression for item in iterable}`

Syntax Structure

Syntax Blueprint
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
price_map = {c['slug']: c['price'] for c in courses}

Code Example

PYTHON Code
# Filtering and Transforming Course Catalog
catalog = [
    {"name": "HTML", "price": 1500, "active": True},
    {"name": "CSS", "price": 1500, "active": True},
    {"name": "JavaScript", "price": 2500, "active": True},
    {"name": "Python", "price": 2500, "active": True},
    {"name": "Legacy Pascal", "price": 1000, "active": False}
]

# 1. List Comprehension: Active course titles formatted
active_titles = [c["name"].upper() for c in catalog if c["active"]]
print("Active Courses:", active_titles)

# 2. List Comprehension: Apply 10% festive discount to all prices
discounted_prices = [int(c["price"] * 0.9) for c in catalog if c["active"]]
print("Discounted Prices:", discounted_prices)

# 3. Dictionary Comprehension: Create lookup mapping title -> price
price_lookup = {c["name"]: c["price"] for c in catalog if c["active"]}
print("Price Lookup Map:", price_lookup)

Explanation of the Code

• `[c["name"].upper() for c in catalog if c["active"]]` combines transformation and filtering into a single line. • `{c["name"]: c["price"] ...}` constructs an instant O(1) hash map lookup dictionary.

Expected Output

Active Courses: ['HTML', 'CSS', 'JAVASCRIPT', 'PYTHON'] Discounted Prices: [1350, 1350, 2250, 2250] Price Lookup Map: {'HTML': 1500, 'CSS': 1500, 'JavaScript': 2500, 'Python': 2500}

Real-World Application

Used across data analysis pipelines with pandas and backend API serialization.

Common Mistakes to Avoid

• Writing overly complex nested comprehensions that harm code readability (if it requires more than two `for` clauses, use a standard loop!). • Using list comprehensions when you only want a side effect like printing.

Quick Practice Challenge

Create a list of squares for all even numbers from 1 to 10 using a list comprehension.

Key Takeaways

• List comprehensions follow `[expr for item in iterable if cond]`. • Dictionary comprehensions follow `{key: val for item in iterable}`. • Fast, idiomatic, and highly readable.