4. Comprehensions and Generators¶
Many programs are built around processing lists, dictionary key/value pairs, and sets. Python provides a special syntax, called comprehensions, for succinctly iterating through these types and creating derivative data structures. Comprehensions can significantly increase the readability of code performing these common tasks and provide a number of other benefits.
This style of processing is extended to functions with generators, which enable a stream of values to be incrementally returned by a function. The result of a call to a generator function can be used anywhere an iterator is appropriate (e.g., for loops, starred expressions). Generators can improve performance, reduce memory usage, and increase readability.
- 4.1. Use Comprehensions Instead of map and filter
- 4.2. Avoid More Than Two Control Subexpressions in Comprehensions
- 4.3. Avoid Repeated Work in Comprehensions by Using Assignment Expressions
- 4.4. Consider Generators Instead of Returning Lists
- 4.5. Be Defensive When Iterating Over Arguments
- 4.6. Consider Generator Expressions for Large List Comprehensions
- 4.7. Compose Multiple Generators with yield from
- 4.8. Avoid Injecting Data into Generators with send
- 4.9. Avoid Causing State Transitions in Generators with throw
- 4.10. Consider itertools for Working with Iterators and Generators
- 4.11. zip_longest
- 4.12. dropwhile