Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
How to Group Data in Python with defaultdict and Comprehensions
Group a list of items by a computed key using a defaultdict-based generator helper and an alternative dictionary comprehension approach.
from collections import defaultdict
def group_by(data, key_func):
"""Group items in data by the value returned by key_func."""
result = defaultdict(list)
for item in data:
result[key_func(item)].append(item)
return dict(result)
def group_by_comprehension(data, key_func):
"""Same grouping …
How to Use List Comprehensions and Generators to Format Data in Python
A beginner-friendly helper that formats dictionaries into strings using a list comprehension and generates squared numbers lazily with a generator.
def format_data(items):
"""Format a list of dictionaries into readable strings."""
formatted = [
f"{item.get('name', 'Unknown')}: {item.get('value', 0)} units"
for item in items
if item.get('value', 0) > 0
]
return formatted if formatted else ["No positive values found"]
def g…
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.