List Comprehensions vs For loops in python

(Comments)

Let us take a scenario where I want to get the list of even numbers from a given range of numbers. We can get the list of even numbers using the for loop as shown below.

even_list = []
for i in range(10000):
    if i%2 == 0:
        even_list.append(i)

As shown in the above code, we are trying to create a list of even numbers from 0 to 9999 The same can be achieved using list comprehension in a one-line as shown below

even_list =[i for i in range(10000) if i%2==0]

So for creating a new list, when we compare the speed of execution in the case of for loop and list comprehension, list comprehension is two times faster than the for-loop. The performance of the list comprehension decreases a bit with the increase in the complexity of the operation performed, but still, list comprehension manages to have better processing speed than the for-loop. In the above example, the i%2 operation is a simple operation, so the speed of the list comprehension is 2 times better than the for-loop. Let us take the below example

list1 = []
for i in range(10000):

    list1.append((i*3)**4)

Here, we are multiplying every element with 3 and then the multiplication result is performed an exponentiation operation with 4 , and this is a complex operation The equivalent list comprehension logic is shown below

list2 =[(i*3)**4 for i in range(10000)]

Even, in this case, the list comprehension has better performance than for loop, but it is not 2 times faster now, it is more like 1.2 times faster than for loop, so definitely the performance of the list comprehension decreases with the increase in the complexity of the operation.

Comments

Recent Posts

Archive

2022
2021
2020
2019
2018
2017
2016
2015
2014

Tags

Authors

Feeds

RSS / Atom