all
can take a generator208 else:
209 project = mr.get_project(models[0].projectId)
210 # Ensures that all models are in the same project
211 if not all([model.projectId == project.id for model in models]):212 raise ValueError(
213 "Not all models are contained within the same project. Try "
214 "specifying a project in the arguments and verify that all models"
The built-in function being used does not require comprehension and can work directly with a generator expression.
Using a generator expression within these functions is faster than using a comprehension:
all
any
enumerate
iter
itertools.cycle
itertools.accumulate
The inbuilt functions all()
and any()
in Python also support short-circuiting (evaluation stops as soon as the overall return value of the function is known), but this behavior is lost if you use a list comprehension. This affects performance.
# Takes a very long time to run
all_evens = all([n % 2 == 0 for n in range(100000000)])
if all_evens:
print('All numbers are even!')
# No list comprehension, runs instantly as `1` is found to be not even
all_evens = all(n % 2 == 0 for n in range(100000000))
if all_evens:
print('The numbers are all even!')