Skip to content

Comprehension to generator

Sourcery refactoring id: comprehension-to-generator

Description:

Replace unneeded comprehension with generator

Before:

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

After:

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

Explanation:

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'

Back to top