C-style for loop vs Pythonic for loop

Posted by Afsal on 22-Apr-2022

Hi Pythonistas, Today we are going to analyze the performance of the difference of C-style for loop vs Pythonic for loop

Let's consider the example

The c style for loop

data = ["a", "b", "c", "d", "e", "f"]

def loop_using_cstyle():
    for index in range(len(data)):
        item = data[index]
        a = item + "test"

Pythonic loop style

def using_pythonic_for_loop():
    for item in data:
        a = item + "test"

Analysis using the timeit module

time_taken = timeit.timeit(loop_using_cstyle, number=1000_000)

print("Time taken by c-style for loop:  ", time_taken)

time_taken = timeit.timeit(using_pythonic_for_loop, number=1000_000)

print("Time taken by pythonic for loop: ", time_taken)

Output

Time taken by c-style for loop: 0.4804183149972232

Time taken by pythonic for loop:  0.2922558329992171

Why

If we analyze the code we can see an additional step for accessing the nth index of the array. But in a pythonic way, there is no additional access to the element using index so it becomes faster

Tip

For iterating over an iterable always use the pythonic way of for loop which is faster and the code looks more pythonic

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