Loop vs Comprehension

Posted by Afsal on 22-Jul-2022

Hi Pythonistas!

Today we are going to compare the speed difference between a loop and list comprehension. Let's consider the example. 

Code

import timeit

def using_loop():
    numbers = list(range(50))
    double = []
    for number in numbers:
        double.append(number * 2)
    return double

def using_comprehension():
    numbers = list(range(50))
    return [number * 2 for number in numbers ]

time_taken = timeit.timeit(using_loop, number=1000_000)
print("Time taken for using_loop", time_taken)

time_taken = timeit.timeit(using_comprehension, number=1000_000)
print("Time taken for using_comprehension", time_taken)

Output

Time taken for using_loop 2.5781862180001553

Time taken for using_comprehension 1.8577961320002032

Why:

 

If we look into the internals of both the code append method makes the code slower. But for list comprehension python is internally called a bytecode called LIST_APPEND. This make the comprehension more faster than the loop. Another thing is it make the code more pythonic also

Hope you have learned something from this post. Please share your valuable suggestion at afsal@parseltongue.co.in