List Comprehension
A list comprehension builds a list from an iterable in one expression: [expression for item in iterable]. It replaces the pattern of creating an empty list, looping, and appending. The result is written first and the source second, and an optional if at the end keeps only the items that pass: [n for n in range(10) if n % 3 == 0].
The same shape builds other collections. Braces with a colon produce a dictionary comprehension, {code: len(code) for code in codes}, and braces without one produce a set comprehension. Parentheses produce a generator expression, which yields values one at a time instead of building the whole collection, so it suits a large source or a result consumed once by sum() or a loop. A generator is consumed as it is iterated and does not restart on a second pass. Two for clauses iterate nested sources from left to right, and the loop variable of a comprehension does not leak into the surrounding scope.
A comprehension can avoid some overhead of an explicit append loop, but the expression, interpreter, and workload determine the result. Measure equivalent code on the same inputs with repeated timings before rewriting it for speed. Compact syntax alone does not prove faster execution.
Readability usually decides. A comprehension is clearest when it maps or filters in a single step. Prefer an ordinary loop when the body needs several statements, when conditions stack up, when nesting makes the expression hard to read, or when the loop does work other than producing the result, such as logging or writing files. A comprehension whose purpose is only its side effects should be a loop.
References: List comprehensions, Displays for lists, sets and dictionaries. See it in use in Python Collections and Comprehensions.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
