result = []
for i in range(0,20):
result.append(i)
When you use a for loop, on every iteration, you have to look up the variable holding the list and then call its append() function. A list comprehension can be faster than a for loop because it’s optimized for performance by Python’s internal mechanisms.
result = []
for i in range(0,20):
result.append(i)
result = [i for i in range(0,20)]
This rule is relevant for scenarios where is needed a simple iteration. The list comprehensions are often not only more readable but also faster than using "for loops." They can simplify the code, but if you put too much logic inside, they will instead become harder to read and understand.
Processor: Apple M1
RAM: 16 Go
CO2 Emissions Measurement: Using CodeCarbon
Two approaches were benchmarked: - Non-compliant: For loop - Compliant: List comprehension
The result of the tests determinated that the list comprehensions can be more readable, but also an alternative to reduce the C02 emissions.