Skip to content

Comprehension to Generator

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: comprehension-to-generator

Section titled “Sourcery refactoring id: comprehension-to-generator”

Replace unneeded comprehension with generator

hat_found = any([is_hat(item) for item in wardrobe])
hat_found = any(is_hat(item) for item in wardrobe)

Functions like any, all and sum allow you to pass in a generator rather than a collection. Doing so removes a pair of brackets, making the intent slightly clearer. It will also return immediately if a hat is found, rather than having to build the whole list. This lazy evaluation can lead to performance improvements.

Note that we are actually passing a generator into any() so strictly speaking the code would look like this:

hat_found = any((is_hat(item) for item in wardrobe))

but Python allows you to omit this pair of brackets.

The standard library functions that accept generators are:

"all", "any", "enumerate", "frozenset", "list", "max", "min", "set", "sum", "tuple"