Use Any¶
Sourcery refactoring id: use-any
¶
Description:¶
Use any
rather than a for
loop
Before:¶
found = False
for hat in hats:
if hat == SOMBRERO:
found = True
break
After:¶
found = any(hat == SOMBRERO for hat in hats)
Explanation:¶
A common pattern is that we need to find if some condition holds for one or all of the items in a collection.
Using Python's any()
and all()
built in functions is a more concise way of
doing this than using a for
loop.
any()
will return True
when at least one of the elements evaluates to
True
, all()
will return True
only when all the elements evaluate to
True
.
These will also short-circuit execution where possible. If the call to any()
finds an element that evalutes to True
it can return immediately. This can
lead to performance improvements if the code wasn't already short-circuiting.