Learn Python List Comprehension In 2023 (With Examples)
List Comprehension is a method or approach of creating a new list in Python based on any existing list. For example, if you have a list ‘List_A‘ with string values and you want to create a new list ‘List_B‘ based on the values present in ‘List_A‘ with a condition that elements or values of ‘List_B‘ contain the character ‘A‘ in it. In this article, we will learn Python list comprehension and its use using real-life examples.
Advantages of Using List Comprehension
- List comprehension requires a shorter syntax or fewer lines of codes
- It is more efficient that normal loops in terms of time and space
- It converts the iterative statement or syntax into a formula which is more readable and understandable
Basic Syntax of Python List Comprehension
new_list = [expression for item in iterable if condition == True]
For example, given a list ‘foo’ = [“A”, “BCD”, “FGH”, “AK”, “EA”], create a new list ‘bar’ using the given list that contains elements of ‘foo’ with character ‘A’ in it.
1 Approach- Using For Loop
In this approach, we will use a simple for loop to iterate through each element. And then check the condition using the if statement and store the results in a new empty list.
foo = ["A", "BCD", "FGH", "AK", "EA"]
bar = []
for x in foo:
if "A" in x:
bar.append(x)
print(bar)
Output
>> ['A', 'AK', 'EA']
2 Approach- Using List Comprehension
Now, we will see how we can write the above syntax
bar = [x for x in foo if "A" in x]
print(bar)
Output
>> ['A', 'AK', 'EA']
We can observe that the complete syntax has been reduced to a single line of code.
Compare Time Complexity of For Loop and List Comprehension
We will check the time taken to execute the Python for loop and Python list comprehension using a simple example.
Scenario: Create a list using a range provided by the user and store the square of each element in the list to a new list.
# Import required module - time to calculate the execution time
import time
# create function to implement for loop
def for_loop(n):
result = []
for x in range(n):
result.append(x**2)
return result
# create function to implement list comprehension
def list_comprehension(n):
return [x**2 for x in range(n)]
# Calculate and display the time takens by for_loop(10**6): where n = 10**6
start = time.time()
for_loop(10**6)
end = time.time()
print('Time taken for_loop:',round(end-start,2))
Output
>> 0.33
# Calculate and display the time takens by list_comprehension(10**6): : where n = 10**6
start = time.time()
list_comprehension(10**6)
end = time.time()
print('Time taken for list_comprehension:',round(end-start,2))
Output
>> 0.25
“List comprehension” is faster than “for loop”.
Some More Examples to Learn Python List Comprehension
1. Display squares of odd numbers from 1 to 15
# print squares of odd numbers from 1 to 15
squares = [n**2 for n in range(1, 16) if n%2!=0]
print(squares)
Output
>> [1, 9, 25, 49, 81, 121, 169, 225]
2. Display squares of even numbers from 1 to 15
# print squares of odd numbers from 1 to 15
squares = [n**2 for n in range(1, 16) if n%2==0]
print(squares)
Output
>> [4, 16, 36, 64, 100, 144, 196]
3. Example of Nested List Comprehensions
Nested List Comprehension is the list comprehension within another list comprehension.
# create the given matrix using List Comprehension
[[0,1,2,3,4],
[0,1,2,3,4],
[0,1,2,3,4]]
matrix = [[j for j in range(5)] for i in range(3)]
print(matrix)
Output
>> [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
In the above example, the first list comprehension is used to print the columns and the second is for printing the rows.