The Python List Comprehensions provides an easy and straightforward way to create a list based on another list or some iterables. The fewer lines of code, easy to read syntax of this Python List Comprehension, helps us to write more complex functionalities elegantly.
The syntax of the Python List Comprehensions
[output_expression for item in List] [output_expression for item in List if condition] [output_expression If Else conditions for item in List]
List Comprehensions Examples
The following examples helps us to learn the Python List Comprehensions.
Simple Python List Comprehensions Examples
Before we start using the Python list comprehensions, let us see the traditional approach to achieve the same result. The following list comprehensions code uses for loop to iterate list items and appending each item to a new list. In short, we are copying list items to an entirely new list.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_list = []
for num in numbers:
new_list.append(num)
print(new_list)
TIP: I suggest you refer to the Python List and Python List functions from Python page.
In general, we use for loop syntax structure along with append function to iterate list items and adding them. However, you can use Python List comprehensions to get that result. It is easy to read and takes less time to execute.
Here, we are using a common approach, and the list comprehension approach. We used the same for loop but removed the append function.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_list = [] for num in numbers: new_list.append(num) print(new_list) print("===================") my_list = [num for num in numbers] print(my_list)
You can see this Python list comprehension example also. Here, we are multiplying each list item with 2. If you look closely, we used the same for loop in both examples, but the only difference is the append function.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_list = [] for num in numbers: new_list.append(num * 2) print(new_list) print("===================") my_list = [num * 2 for num in numbers] print(my_list)
We are using the List comprehensions to multiply list items with 2, 3, and finding each item’s square.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
double_list = [num * 2 for num in numbers]
print(double_list)
triple_list = [num * 3 for num in numbers]
print(triple_list)
square_list = [num ** 2 for num in numbers]
print(square_list)
It is the same as the above list comprehension example. However, this time, we are comparing the regular approach and Python list comprehensions.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_list1 = [] new_list2 = [] new_list3 = [] for num in numbers: new_list1.append(num * 2) new_list2.append(num * 3) new_list3.append(num ** 2) print(new_list1) print(new_list2) print(new_list3) print("===================") double_list = [num * 2 for num in numbers] print(double_list) triple_list = [num * 3 for num in numbers] print(triple_list) square_list = [num ** 2 for num in numbers] print(square_list)
In this list comprehensions example, the first List comprehension multiplies each item with itself and so on. Here, the parenthesis decides the priority of calculation. For example, 2 * 2 + 1 means 4 + 1, whereas 2 * (2 + 1) means 2 * 3 .
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
double_list = [num * num for num in numbers]
print(double_list)
triple_list = [num * num + 1 for num in numbers]
print(triple_list)
square_list = [num * (num + 2) for num in numbers]
print(square_list)
s_list = [num * (num + 4) for num in numbers]
print(s_list)
Python List Comprehension If
In all our previous list comprehension examples, we used for loop to iterate each list item and performing calculations. What if we want to check some conditions using this list comprehensions?
Here, we use the if statement to check and display the even numbers from a numbers list. First, we placed for loop within the [], next we placed the if statement. At last, we placed the appended item before for loop.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_list = [] for num in numbers: if num % 2 == 0: new_list.append(num) print(new_list) print("===================") my_list = [num for num in numbers if num % 2 == 0] print(my_list)
List Comprehension Multiple Conditions
The Python programming language also allows you to use multiple conditions. In this Python list comprehension example, we are using multiple if statements to check the item or value divided by 2 equals to 0. If True, it checks the item is also divisible by 5. If both are true, then that number added to my_list.
new_list = [] for num in range(1, 150): if num % 2 == 0 and num % 5 == 0: new_list.append(num) print(new_list) print("===================") my_list = [num for num in range(1, 150) if num % 2 == 0 if num % 5 == 0] print(my_list)
Python List Comprehension If Else
In this example, we are using the If else in Python list comprehensions. The If else code checks and displays whether the value is even or odd.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers)
my_list = ["Even" if num % 2 == 0 else "Odd" for num in numbers]
print(my_list)
List Comprehensions Nested For Loop
Here, we are printing the multiplication table using the List comprehensions with nested for loops.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list = [[i * j for j in range(1, 11)] for i in range(2, 4)]
print(my_list)
# Same using For loop
print("------------------------------")
for i in range(2, 4):
for j in range(1, 11):
print(f"{i} * {j} = {i * j}")
Transposing the 3 * 3 matrix using the list comprehension. To achieve the same, we need Nested List comprehension in Python.
my_list = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
print(my_list)
new_list = [[row[i] for row in my_list] for i in range(3)]
print(new_list)
The Nested list comprehension to convert the nested list to a normal list.
my_list = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
print(my_list)
new_list = [item for row in my_list for item in row]
print(new_list)
# Same using For loop
print("------------------------------")
for_list = []
for row in my_list:
for item in row:
for_list.append(item)
print(for_list)
In this list comprehension example, first, we used adding each list item in the first list with each list item in the second list. I mean, [10 + 40, 20 + 40, 30 + 40], [10 + 50, 20 + 50, 30 + 50] so on. Within the second statement, we are using the list comprehension to create a list of tuples by combining two lists.
my_list1 = [10, 20, 30]
my_list2 = [40, 50, 60]
new_list = [[i + j for i in my_list1] for j in my_list2]
print(new_list)
print("------------------")
new_list2 = [[(i, j) for i in my_list1] for j in my_list2]
print(new_list2)
List Comprehension String List
So far, we are using the integer list items to perform mathematical calculations. However, you can use this Python List comprehensions on the string list.
In this example, we show how to use the Built-in functions within the List comprehensions. The first list comprehension applies lower function on each list item to convert them to lowercase. The second list applies the upper function to convert the list items to uppercase.
fruits = ['ApplE', 'OraNGe', 'GrAPe', 'BaNAna']
print(fruits)
l_list = [a.lower() for a in fruits]
print(l_list)
u_list = [a.upper() for a in fruits]
print(u_list)
For a better understanding of this list comprehension, we used a few more functions. The first list comprehension used the swapcase function to swap the letter cases. The second list comprehension line used the len function to find and return each item’s length in a string list. Within the last list comprehension, we are capturing the first letter of each item.
fruits = ['ApplE', 'OraNGeS', 'GrAPe', 'BaNAna']
print(fruits)
swap_list = [a.swapcase() for a in fruits]
print(swap_list)
len_list = [len(a) for a in fruits]
print(len_list)
first_letters = [item[0] for item in fruits]
print(first_letters)
In this Python Nested List comprehensions example, we are mixing the numbers and string items. It returns the combination of each fruit with a number. I mean, Apple with 1, 2, 3, 4, 5, Orange with 1, 2, 3, 4, 5 so on.
fruits = ['Apple', 'Orange', 'Grape', 'Banana', 'Kiwi']
numbers = [1, 2, 3, 4, 5]
my_list = [[(fruit, num) for fruit in fruits] for num in numbers]
print(my_list)
# Same using For loop
print("------------------------------")
new_list = []
for fruit in fruits:
for num in numbers:
new_list.append((fruit, num))
print(new_list)
List Comprehensions on String Data
You can also use this list comprehensions on string data. Here, we are extracting each character from a string and creating a new string.
string = 'Python'
print(string)
my_list = [word for word in string]
print(my_list)
# Same using For loop
print("------------------------------")
new_list = []
for word in string:
new_list.append(word)
print(new_list)
In this list comprehensions example, we just changed the string value in the above image to Tutorial Gateway.
string = 'Tutorial Gateway'
print(string)
my_list = [word for word in string]
print(my_list)
# Same using For loop
print("------------------------------")
new_list = []
for word in string:
new_list.append(word)
print(new_list)
Python List Comprehensions Vs Lambda Function
If fewer code lines are our priority, then we are not limited to list comprehensions. You can use the lambda function.
Here, we are using the traditional approach, list comprehension approach, and lambda function to multiply each item in a list with itself. By seeing the code, you can see that the lambda function is also very useful. However, the list comprehension code is easy to read and faster to execute.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_list = [] for num in numbers: new_list.append(num * num) print(new_list) print("===================") my_list = [num * num for num in numbers] print(my_list) print("===================") this_list = list(map(lambda num: num * num, numbers)) print(this_list)
It is another example to differentiate the code readability between the Python List comprehensions and lambda functions.
numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] double_list = [num * 2 for num in numbers] print(double_list) triple_list = [num * 3 for num in numbers] print(triple_list) square_list = [num ** 2 for num in numbers] print(square_list) #Lambda Function Example print("===================") d_list = list(map(lambda num: num * 2, numbers)) print(d_list) t_list = list(map(lambda num: num * 3, numbers)) print(d_list) s_list = list(map(lambda num: num ** 2, numbers)) print(d_list)