Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
Dict Comprehension to Map Keys to Lengths in Python
Build a dictionary that maps each word to its character count using a dictionary comprehension.
words = ["apple", "banana", "cherry", "date", "elderberry"]
word_lengths = {word: len(word) for word in words}
print(word_lengths)
Set Comprehension for Unique Word Lengths in Python
Use a set comprehension to extract unique word lengths from a string, then sort and print the result.
text = "hello world hello python programming"
word_lengths = {len(word) for word in text.split()}
print("Unique word lengths:", word_lengths)
print("Sorted:", sorted(word_lengths))
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.