Use Any
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: use-any
Section titled “Sourcery refactoring id: use-any”Description:
Section titled “Description:”Use any rather than a for loop
Before:
Section titled “Before:”found = Falsefor hat in hats: if hat == SOMBRERO: found = True breakAfter:
Section titled “After:”found = any(hat == SOMBRERO for hat in hats)Explanation:
Section titled “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.