Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
How to Generate Permutations of Length r in Python
Generate all ordered arrangements of length r from a given list of elements using itertools.permutations.
from itertools import permutations
def generate_permutations(elements, r):
"""Generate all r-length permutations of the given elements."""
return list(permutations(elements, r))
if __name__ == "__main__":
elements = ['A', 'B', 'C']
r = 2
result = generate_permutations(elements, r)
print(f"Ele…
How to Slice a Generator with islice in Python
Use itertools.islice to take the first n items from any iterable without materializing the whole sequence into a list.
from itertools import islice
def first_n(iterable, n):
"""Return the first n items from an iterable."""
return list(islice(iterable, n))
if __name__ == "__main__":
numbers = range(10, 100) # large iterable
result = first_n(numbers, 5)
print(result) # [10, 11, 12, 13, 14]
How to filter even numbers with a Python list comprehension
Build a new list of only the even numbers from 1 to 20 using a single list comprehension with a filter condition.
even_numbers = [num for num in range(1, 21) if num % 2 == 0]
print(even_numbers)
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.