Skip to content

    List Comprehensions & Generators

    Python · Intermediate

    Definition

    Comprehensions build lists/dicts/sets in one expression; generators produce values lazily with yield.

    They make code shorter, faster and memory-efficient.

    Diagram

    [x*xfor x in range(5)if x%2==0]

    Flowchart

    Pick iterableApply expressionOptional if filterCollect resultsUse () for lazy generator

    Example: Squares of evens

    print([x*x for x in range(10) if x % 2 == 0])

    Output: [0, 4, 16, 36, 64]

    Key points

    • Generators save memory
    • yield pauses a function
    • Avoid overly complex comprehensions

    Interview questions

    Generator vs list?

    A generator computes items on demand and can be iterated only once.

    More Python topics