all
and any
can take a generator, so constructing a list first may be unnecessary.
A generator returns a single item in the sequence ad hoc, on each iteration, while a list first loads the full list to memory.
any
stops the loops as soon as a truthy is encountered and all
stops the loop as soon as a falsey is encountered, so they lend themselves well to working with generators.
Caution is needed though: it's possible that a developer would want to avoid short-circuiting the loop: when the proper functioning of the code relies on the loop being completed. For example:
In that case the emails would stop being sent as soon as one message failed to send. Probably not what the developer intended to happen.
If our GitHub code review bot spots this issue in your pull request it gives this advice:
1 | + | any([item for item in items]) |
all
and any
can take a generator, so constructing a list first may be unnecessary.
- | any([item for item in items]) |
+ | any(item for item in items) |