List Comprehensions, Dict Comprehensions & Generator Expressions - Python Tutorial #14
Video: List Comprehensions, Dict Comprehensions & Generator Expressions - Python Tutorial #14 by Taught by Celeste AI - AI Coding Coach
Watch full page →List Comprehensions, Dict Comprehensions & Generator Expressions in Python
Python comprehensions provide a concise and readable way to create lists, dictionaries, sets, and generators by iterating over sequences and optionally filtering or transforming items. This tutorial covers basic list comprehensions, conditional filtering, inline if/else transformations, nested comprehensions, dictionary and set comprehensions, and generator expressions, all with practical examples.
Code
# Basic list comprehension: squares of numbers 0 to 5
squares = [x ** 2 for x in range(6)]
print("Squares:", squares) # Output: [0, 1, 4, 9, 16, 25]
# Comprehension with condition: even numbers from 0 to 9
evens = [x for x in range(10) if x % 2 == 0]
print("Evens:", evens) # Output: [0, 2, 4, 6, 8]
# Transform with if/else inside comprehension: label numbers as 'even' or 'odd'
labels = [f"{x} even" if x % 2 == 0 else f"{x} odd" for x in range(6)]
print("Labels:", labels) # Output: ['0 even', '1 odd', '2 even', '3 odd', '4 even', '5 odd']
# Nested list comprehension: flatten a 2D matrix
matrix = [[1, 2, 3], [4, 5, 6]]
flattened = [num for row in matrix for num in row]
print("Flattened:", flattened) # Output: [1, 2, 3, 4, 5, 6]
# Dictionary comprehension: map words to their lengths
words = ["apple", "banana", "cherry"]
lengths = {w: len(w) for w in words}
print("Lengths:", lengths) # Output: {'apple': 5, 'banana': 6, 'cherry': 6}
# Set comprehension: unique lowercase names
names = ["Alice", "Bob", "alice", "bob"]
unique = {n.lower() for n in names}
print("Unique lowercase names:", unique) # Output: {'alice', 'bob'}
# Generator expression: lazily compute squares of 0 to 4
gen = (x ** 2 for x in range(5))
print("Generator output:", list(gen)) # Output: [0, 1, 4, 9, 16]
Key Points
- List comprehensions provide a compact syntax to create lists by iterating and optionally filtering or transforming elements.
- Conditional expressions inside comprehensions allow labeling or modifying elements based on conditions.
- Nested comprehensions can flatten complex structures like matrices or create grids efficiently.
- Dictionary and set comprehensions let you build dictionaries and sets in a similarly concise way.
- Generator expressions create iterators that produce items lazily, saving memory for large datasets.