Home »
Python
Python List Comprehension: Learn with Examples
Python List Comprehension: In this tutorial, we will what is list comprehension and how to create a list using list comprehension with the help of examples.
By Sapna Deraje Radhakrishna Last updated : June 15, 2023
Python List Comprehension
List comprehension is an important feature of Python, it provides shorter syntax to create a new list based on the existing list. List comprehension reduces the number of lines in list creation to a single line.
Syntax
The list comprehension starts with a [ and ], to ensure that the result is a list.
[expression for item in list]
The comprehension can also utilize the if condition.
Grouping elements using list comprehension
Group the common elements to a list: There are two lists with some elements, we have to create a list containing common elements.
Example
# Create two lists
grade_k = ['maddy', 'sriansh', 'owen', 'molly']
grade_first = ['molly', 'owen', 'ricky', 'sid']
# Print original lists
print("Original lists")
print("grade_k:", grade_k)
print("grade_first:", grade_first)
# Grouping common elements
common_names = [a for a in grade_k for b in grade_first if a == b]
# Print new list
print("Result (common_names):", common_names)
Output
Original lists
grade_k: ['maddy', 'sriansh', 'owen', 'molly']
grade_first: ['molly', 'owen', 'ricky', 'sid']
Result (common_names): ['owen', 'molly']
List of EVENs using list comprehension
List of EVEN numbers using list comprehension: Here, we will write a Python program that will create a list of EVEN numbers in a range.
Example
# List of EVEN numbers using
# list comprehension
even_list = [n for n in range(30) if n % 2 == 0]
# Print list
print(even_list)
Output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
List by replacing specific elements using list comprehension
Here, we will write a program to create a new list by replacing all specific elements of an existing list.
Example
# list 1
list1 = ['molly', 'sriansh', 'owen', 'molly']
# print list 1
print("list1:", list1)
# New list by replacing 'molly' with 'alex
newlist = [v if v != 'molly' else 'alex' for v in list1]
# print new list
print("newlist:", newlist)
Output
list1: ['molly', 'sriansh', 'owen', 'molly']
newlist: ['alex', 'sriansh', 'owen', 'alex']
Nested List Comprehensions
Nested list comprehensions allow you to use list comprehension within the list comprehension.
Example
# Create a matrix using
# nested list comprehension
mat = [[j for j in range(4)] for i in range(2)]
# Print list akka matrix
print(mat)
Output
[[0, 1, 2, 3], [0, 1, 2, 3]]
Advantages of using comprehension
- Comprehensions requires less code. Python interpreter is optimized to run comprehensions as quickly as possible.
- Comprehensions execute faster than for loop.
- Comprehensions can be used in places where for loop cannot be used. All the comprehensions appear to the right of the assignment operator, which is something for loop cannot do.