Reference library

Comprehensions & generators

List/dict/set comprehensions, generator expressions, and lazy iteration.

2 matches
Comprehensions & generators easy

Dict Comprehension to Map Keys to Lengths in Python

Build a dictionary that maps each word to its character count using a dictionary comprehension.

dictionary comprehension len
Python
words = ["apple", "banana", "cherry", "date", "elderberry"]

word_lengths = {word: len(word) for word in words}

print(word_lengths)
14 0 Open
Comprehensions & generators easy

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.

set comprehension unique word lengths
Python
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))
10 0 Open

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.