Time Analysis in List Comprehensions and Loop
The list comprehensions in Python are more efficient both computationally and in terms of coding space and time than a for a loop. Typically, they are written in a single line of code. The below program depicts the difference between loops and list comprehension based on performance.
Python
# Import required module import time # define function to implement for loop def for_loop(n): result = [] for i in range (n): result.append(i * * 2 ) return result # define function to implement list comprehension def list_comprehension(n): return [i * * 2 for i in range (n)] # Driver Code # Calculate time taken by for_loop() begin = time.time() for_loop( 10 * * 6 ) end = time.time() # Display time taken by for_loop() print ( 'Time taken for_loop:' , round (end - begin, 2 )) # Calculate time takens by list_comprehension() begin = time.time() list_comprehension( 10 * * 6 ) end = time.time() # Display time taken by for_loop() print ( 'Time taken for list_comprehension:' , round (end - begin, 2 )) |
Output
Time taken for_loop: 0.39 Time taken for list_comprehension: 0.35
From the above program, we can see list comprehensions are quite faster than for loop.
Python – List Comprehension
A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list.
Example:
Python
numbers = [ 12 , 13 , 14 ,] doubled = [x * 2 for x in numbers] print (doubled) |
Output
[24, 26, 28]