Python

Python

Made by DeepSource

Unnecessary comprehension PTC-W0016

Performance
Major
Autofix

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!')