Skip to content
    Pythonia

    ADVANCED PYTHON · 10 MIN

    Comprehensions, Generators & Decorators

    Shortcuts that make Python code shorter, lazier and more reusable.

    PYRA explains

    • List comprehension: [x*x for x in nums if x > 0] builds a list in one line.
    • A generator uses yield to produce values one at a time, saving memory.
    • A decorator wraps a function to add behaviour (logging, timing, caching) without editing it.

    Real world: A tap (generator) gives water as you need it instead of filling a whole tank first.

    Code

    def countdown(n):
        while n > 0:
            yield n
            n -= 1
    print(list(countdown(3)))
    def shout(fn):
        return lambda *a: fn(*a).upper()
    @shout
    def hello(name):
        return "hi " + name
    print(hello("cubo"), [x * x for x in range(5) if x % 2 == 0])
    Output ›
    [3, 2, 1]
    HI CUBO [0, 4, 16]
    Try it in the online compiler →

    Checkpoint quiz

    Which keyword turns a function into a generator?