devnotes.

List Comprehensions and Generator Expressions

A list comprehension builds a new list from an iterable in a single, readable expression — one of the most distinctively "Pythonic" pieces of syntax.

squares = [n ** 2 for n in range(10)]              # [0, 1, 4, 9, ..., 81]
evens = [n for n in range(20) if n % 2 == 0]        # filter with an if clause
pairs = [(x, y) for x in range(3) for y in range(3)] # nested loops -> 9 tuples

names = ["Rahim", "karim", "NADIA"]
cleaned = [name.strip().title() for name in names]   # transform each element

squares_dict = {n: n ** 2 for n in range(5)}          # dict comprehension
unique_lengths = {len(name) for name in names}         # set comprehension

# Generator expression — same syntax, () instead of [] — computes lazily
sum_of_squares = sum(n ** 2 for n in range(1000000))   # never builds a full list in memory

The general form is [expression for item in iterable if condition] — read it as "for each item in iterable, if condition holds, compute expression and collect the results into a list." Multiple for clauses can be chained for nested loops, and the same syntax works for dict comprehensions ({k: v for ...}) and set comprehensions ({x for ...}).

A generator expression — identical syntax but with () instead of [] — produces values lazily, one at a time as they're requested, instead of building the entire result in memory upfront. For sum(n ** 2 for n in range(1000000)), this means the program never holds a million-element list at once, only ever the current value being summed — a significant memory saving for large or infinite sequences, and the reason generator expressions are preferred over list comprehensions whenever the full list isn't actually needed afterward.

List comprehensions are idiomatic and often faster than the equivalent for loop with .append(), but readability should still come first — a comprehension nested three levels deep with multiple conditions is usually better rewritten as an explicit loop.

List Comprehensions and Generator Expressions in Python | DevNotes