Blog | CoWhite Softwarehttp://django.cowhite.com/blog/2022-01-02T12:59:58+00:00BlogList Comprehensions vs For loops in python2022-01-02T12:59:58+00:00bhaskar/blog/author/bhaskar/http://django.cowhite.com/blog/lists-comprehensions-vs-for-loops-in-python/<p>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.</p> <div class="codehilite"><pre>even_list = [] for i in range(10000): if i%2 == 0: even_list.append(i) </pre></div> <p>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</p> <div class="codehilite"><pre>even_list =[i for i in range(10000) if i%2==0] </pre></div> <p>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</p> <div class="codehilite"><pre>list1 = [] for i in range(10000): list1.append((i*3)**4) </pre></div> <p>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</p> <div class="codehilite"><pre>list2 =[(i*3)**4 for i in range(10000)] </pre></div> <p>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.</p>