This section focuses on iterators, generators, and comprehensions, which are essential for writing efficient and Pythonic code. You'll learn how to handle data streams and create concise loops to enhance your programming capabilities.
8 audio · 1:52
Nortren·
When should you use a comprehension versus a generator expression?
0:15
Use a list, dict, or set comprehension when you need the entire collection materialized, for example to iterate it multiple times or pass it to a function expecting a list. Use a generator expression when you only need to iterate once and want to save memory, especially for large or infinite sequences.
Map takes a function and one or more iterables and returns an iterator that applies the function to each element. In Python 3, map is lazy and returns a map object, not a list. For most cases, a generator expression or list comprehension is considered more readable than map.
Filter takes a predicate function and an iterable and returns an iterator over elements for which the predicate returns true. Like map, filter is lazy in Python 3. Comprehensions with an if clause are generally preferred for readability.
Reduce, available in functools, applies a binary function cumulatively to elements of an iterable, reducing it to a single value. It is the right tool for aggregations that cannot be expressed with sum, max, min, or any. For most everyday cases, an explicit loop or sum is clearer.
Enumerate wraps an iterable and produces tuples of an index and the element. The default starting index is zero, but you can pass a start argument. It is the idiomatic way to iterate when you need both the position and the value.
Zip takes multiple iterables and produces tuples of corresponding elements, stopping at the shortest. In Python 3 it is lazy. The strict variant zip with strict equals True, added in Python 3.10, raises an error if the iterables have different lengths.
Chain takes multiple iterables and produces their elements in sequence, as if they were a single iterable. It is the lazy equivalent of concatenating lists. Chain.from_iterable takes a single iterable of iterables and chains them, useful for flattening one level.
Groupby takes an iterable and produces consecutive groups of equal elements, returning each group as a key and an iterator. It groups only adjacent equal elements, so the input usually needs to be sorted first. It is useful for run-length encoding and similar patterns.
---