Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
Convert Data in Python with Comprehensions and Generators
Convert mixed data to integers, filter and transform numbers, and extract fields from dicts using list comprehensions and generator expressions.
def convert_numbers(data):
"""Convert a list of mixed values into integers using a comprehension."""
return [int(item) for item in data if item is not None]
def double_even_numbers(numbers):
"""Double only even numbers using a generator expression."""
return (n * 2 for n in numbers if n % 2 == 0)
d…
How to Sort Data with Comprehensions and Generators in Python
Sort a list of tuples by a key, then use a list comprehension to extract names and a generator to square high ranks.
data = [("Anna", 3), ("Ben", 1), ("Clara", 2), ("Dan", 5), ("Eve", 4)]
# Comprehension: list of tuples (name, rank) sorted ascending by rank
sorted_by_rank = sorted(data, key=lambda x: x[1])
# Comprehension: extract just the names in rank order
names_in_rank_order = [name for name, rank in sorted_by_rank]
# Generat…
How to Use List Comprehensions and Generators in Python
Analyze a list of numbers using a list comprehension to square evens, a generator for sum, and a generator expression for the maximum squared value.
def analyze_numbers(numbers):
squared = [n ** 2 for n in numbers if n % 2 == 0]
total = sum(n for n in numbers)
max_squared = max((n ** 2 for n in numbers), default=0)
return squared, total, max_squared
if __name__ == "__main__":
data = [1, 2, 3, 4, 5, 6]
evens_squared, total_sum, max_sq = an…
How to Use List Comprehensions and Generators to Transform Data in Python
Transform a list of integers by squaring even numbers with a list comprehension and cubing odd numbers with a generator.
def transform_data(data):
"""
Transform a list of integers:
- squares of even numbers using a list comprehension
- cubes of odd numbers using a generator
"""
squares = [num ** 2 for num in data if num % 2 == 0]
cubes = (num ** 3 for num in data if num % 2 != 0)
return squares, cubes
i…
Browse by section
Each section groups closely related Python snippets.
Comprehensions & generators — Python code examples
What you will find here
This page collects comprehensions & generators snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.