› Module 12: Advanced Python › 12.1 List Comprehensions
M O D U L E

Module 12: Advanced Python

The idiomatic, distinctly 'Pythonic' features that set apart experienced Python code from a direct, line-by-line translation of C or Java.

12.1 List Comprehensions

A list comprehension builds a brand-new list from an iterable in a single, readable expression: [x*x for x in range(5)] replaces what would otherwise be a multi-line loop calling .append() repeatedly.

Comprehensions can also filter out unwanted elements with an if clause ([x for x in nums if x % 2 == 0]), and equivalent comprehension syntax exists for building dictionaries and sets too ({k: v for k, v in pairs}) — making this one of Python's most distinctive and widely-used idioms.

Comprehension vs. The Equivalent Loop (from the Guide)

# COMPREHENSION VS. THE EQUIVALENT LOOP
squares = [x*x for x in range(5)]

# exactly equivalent to:
squares = []
for x in range(5):
    squares.append(x*x)

Dictionary and Set Comprehensions

# Set comprehension (automatically deduplicates):
unique_lengths = {len(w) for w in ["apple", "banana", "fig", "pear"]}

# Dict comprehension:
names = ["Amit", "Neha", "Kiran"]
name_lengths = {name: len(name) for name in names}
# Result: {'Amit': 4, 'Neha': 4, 'Kiran': 5}

12.2 Iterators and Generators

An iterable is anything you're able to loop over — a list, a string, an open file. An iterator is the underlying object that actually produces the values one at a time, via repeated calls to next(), while quietly tracking its own current position.

A generator function — written just like a normal function, but using yield instead of return — automatically creates an iterator for you, computing each value lazily, only the moment it's actually needed, rather than building the entire sequence in memory up front.

This makes generators the ideal tool for processing very large, or even genuinely infinite, sequences efficiently.

def gen(): yield 1; yield 2 yield 3 (lazy generator object) next(g) → 1 next(g) → 2 ...one value at a time
Figure 12.1 — A generator computes each value on demand, and never holds the whole sequence in memory at once.

12.3 Decorators

A decorator is a function that wraps around another function to extend or modify its behavior — all without touching that function's actual source code.

It's applied with the distinctive @decorator_name syntax, placed directly above the function definition it applies to.

Decorators are the standard tool for handling cross-cutting concerns like logging, timing, access control, and caching — functools.lru_cache is a ready-made, built-in decorator that automatically caches a function's results so repeated calls with the same arguments skip re-computation entirely.

A Minimal Decorator (from the Guide)

# A MINIMAL DECORATOR
def my_decorator(func):
    def wrapper():
        print('before')
        func()
        print('after')
    return wrapper

@my_decorator
def say_hi():
    print('hi')

say_hi() # now actually runs wrapper() instead
# Output:
# before
# hi
# after

12.4 Virtual Environments & the Standard Library

Beyond venv's role in isolating a project's dependencies, Python ships with what's often called a "batteries-included" standard library — an extensive set of built-in modules covering:

  • Dates and Times: datetime, time, zoneinfo
  • Filesystem Paths: os, pathlib, shutil
  • Structured Data: json, csv, sqlite3
  • Text & Pattern Matching: re (regular expressions)
  • Mathematics & Logic: math, random, statistics, itertools, functools

frequently meaning you don't need to install any third-party package at all for common tasks.

Combined with PyPI's enormous third-party ecosystem — NumPy, pandas, Django, Flask, TensorFlow, and thousands more — this combination is a major reason Python has become a default choice across web development, data science, automation, and AI/ML.

MODULE COMPREHENSIVE QUIZ

Module 12 Final Quiz

Test your understanding across all 4 topics of this module with interview-grade questions, tricky edge cases, and code output predictions.

Take Module 12 Final Quiz →
Yukti Mascot