Unnecessary comprehension -
all
can take a generator 40
41 def get_number(self, min_max=[1, 10]):
42 """Get a random number between min and max."""
43 assert all([isinstance(i, int) for i in min_max]) 44 return random.randint(*min_max)
45
46
Description
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.
Bad practice
# 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!')
Recommended
# 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!')