Should I use a for-loop or a list comprehension in Python?

Should you use a for-loop?

a = range(100000)
b = []
for i in a:

Or a list comprehension?

a = range(100000)
b = [i*2 for i in a]

The short answer is: use a list comprehension. For a longer answer see the advantages and disadvantages of each method.

Advantages of a for loop:

1. For-loops are more readable and easier to comprehend. It comes more naturally to write a for-loop than it does for a list comprehension.

Advantages of a list comprehension:

1. List comprehensions are shorter. A list comprehension can be written in one line whereas a for-loop requires a block of code.
2. List comprehensions are faster:

import timeit
code_to_test = """
a = range(100000)
b = []
for i in a:
elapsed_time = timeit.timeit(code_to_test, number=100)/100

The code above measures the execution time of the for-loop. The output is 0.018875499800778926 seconds. 

The code below measures the execution time of a list comprehension that generates the same output as the for-loop above. The output this time in the same machine is  0.007040239260531962 seconnds. So, the list comprehension was 2-3 times faster. 

Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.

Mailing List

We will keep you Python-motivated if you subscribe below.