Comprehension to Generator¶
Sourcery refactoring id:
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)
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
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"