Reference library

Comprehensions & generators

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

1 match
Comprehensions & generators easy

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.

comprehensions generators list-comprehension
Python
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…
15 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.