Python List Comprehensions provides an easy and straightforward way to create a list based on others or some iterables. The fewer lines of code easy to read syntax of this Python List Comprehension syntax helps us to write more complex functionalities elegantly, and it is
[output_expression for item in L1] [output_expression for item in L2 if condition] [output_expression If Else conditions for item in L3]
The above syntax shows that the Python list comprehension consists of a for loop to read all the elements in an existing list. It is one of the powerful functions that can make the code more readable.
Python List Comprehensions Examples
The following examples help us to learn this.
Simple Python List Comprehension Example
Before we start using this, let us see the traditional approach to achieve the same result.
In general, we use the for loop syntax structure along with the append function to iterate elements and add them. However, you can use Python List comprehensions to get the same output. It is easy to read and takes less time to execute.
The following code uses for loop iterable objects and list comprehension to iterate items and append each item to a new one. In short, we are copying items to an entirely new one.
Here, we are using a common approach and the expression approach. We used the same for loop but removed the append function. I suggest you refer to the List, for loop, and functions from the Python page. As you can notice, the code has been written in a single line, and it returns a new list.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new = [] for num in numbers: new.append(num) print(new) print("===================") my = [num for num in numbers] print(my)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
===================
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
You can see this Python list comprehension example also. Here, we are multiplying each item by 2. If you look closely, we used the same for loop for both examples, but the only difference is the append function.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] mul = [] for num in numbers: mul.append(num * 2) print(mul) print("===================") my = [num * 2 for num in numbers] print(my)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
===================
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
We use the Python List comprehensions to multiply elements by 2 and 3 and find each item’s square.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] doubleA = [i * 2 for i in a] print(doubleA) tripleA = [i * 3 for i in a] print(tripleA) squareA = [i ** 2 for i in a] print(squareA)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
It is the same as the above example. However, this time, we are comparing the regular approach also.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new1 = [] new2 = [] new3 = [] for num in numbers: new1.append(num * 2) new2.append(num * 3) new3.append(num ** 2) print(new1) print(new2) print(new3) print("===================") doubleN = [num * 2 for num in numbers] print(doubleN) tripleN = [num * 3 for num in numbers] print(tripleN) squareN = [num ** 2 for num in numbers] print(squareN)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
===================
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In this example, the first statement multiplies each item with itself and so on. Here, the square brackets decide 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] doubleLi = [n * n for n in numbers] print(doubleLi) tripleLi = [n * n + 1 for n in numbers] print(tripleLi) squareLi = [n * (n + 2) for n in numbers] print(squareLi) s_li = [n * (n + 4) for n in numbers] print(s_li)
Python List Comprehension If
In all our previous examples, we used for loop to iterate each element and perform calculations. What if we want to check some conditions using this one?
Here, we use the if statement to check and display the even numbers from numbers. First, we placed for loop within the []. Next, we placed the if statement. At last, we placed the appended item before for loop.
n1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = [] for y in n1: if y % 2 == 0: a.append(y) print(a) print() b = [y for y in n1 if y % 2 == 0] print(b)
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]
Python List Comprehension Multiple Conditions
This programming language also allows you to use multiple conditions. In this example, we use multiple if statements to check the item or value divided by 2 equals 0. If True, it checks the item is also divisible by 5. If both are true, then that number is added to a.
a = [] for n in range(1, 150): if n % 2 == 0 and n % 5 == 0: a.append(n) print(a) print() b = [n for n in range(1, 150) if n % 2 == 0 if n % 5 == 0] print(b)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140]
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140]
Python List Comprehension If Else
In this example, we are using the If else. The If else code checks and displays whether the value is even or odd.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(a) b = ["Even" if i % 2 == 0 else "Odd" for i in a] print(b)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']
Nested For Loop
Here, we are printing the multiplication table using the nested for loops. The same can be done by nesting.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = [[i * j for j in range(1, 11)] for i in range(2, 4)] print(a) # Same using For loop print() for i in range(2, 4): for j in range(1, 11): print(f"{i} * {j} = {i * j}")
[[2, 4, 6, 8, 10, 12, 14, 16, 18, 20], [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]]
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
We need Nested List comprehension in Python to Transpose the 3 * 3 matrix.
a = [[10, 20, 30], [40, 50, 60], [70, 80, 90]] print(a) b = [[row[i] for row in a] for i in range(3)] print(b)
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
[[10, 40, 70], [20, 50, 80], [30, 60, 90]]
The Nested one converts the nested to a normal.
c = [[10, 20, 30], [40, 50, 60], [70, 80, 90]] print(c) d = [item for row in c for item in row] print(d)
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
[10, 20, 30, 40, 50, 60, 70, 80, 90]
In this Python list comprehension example, we first added each item in the first one, i.e., a, with each element in the second. I mean, [10 + 40, 20 + 40, 30 + 40], [10 + 50, 20 + 50, 30 + 50] so on.
Within the second statement, we use this one to create a list of tuples by combining two existing ones.
a = [10, 20, 30] b = [40, 50, 60] c = [[i + j for i in a] for j in b] print(c) print() d = [[(i, j) for i in a] for j in b] print(d)
[[50, 60, 70], [60, 70, 80], [70, 80, 90]]
[[(10, 40), (20, 40), (30, 40)], [(10, 50), (20, 50), (30, 50)], [(10, 60), (20, 60), (30, 60)]]
String Example
So far, we are using integer items to perform mathematical calculations. However, you can use this Python List comprehension on the string.
This example shows how to use the Built-in functions within this. The first one applies lower on each item to convert them to lowercase. The second one applies the upper to convert the items to uppercase.
For a better understanding of this, we used a few more functions. The first one used the swapcase to swap the letter cases. The second line used the len function to find and return each item’s length in a string. Within the last one, we capture each item’s first letter.
fruits = ['ApplE', 'OraNGe', 'GrAPe', 'BaNAna'] print(fruits) low = [a.lower() for a in fruits] print(low) upp = [a.upper() for a in fruits] print(upp) swap = [a.swapcase() for a in fruits] print(swap) ln = [len(a) for a in fruits] print(ln) first = [item[0] for item in fruits] print(first)
['ApplE', 'OraNGe', 'GrAPe', 'BaNAna']
['apple', 'orange', 'grape', 'banana']
['APPLE', 'ORANGE', 'GRAPE', 'BANANA']
['aPPLe', 'oRAngEs', 'gRapE', 'bAnaNA']
[5, 7, 5, 6]
['A', 'O', 'G', 'B']
In this Python Nested List comprehensions example, we mix 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] f = [[(fruit, num) for fruit in fruits] for num in numbers] print(f) # Same using For loop print() g = [] for fruit in fruits: for num in numbers: g.append((fruit, num)) print(g)
[[('Apple', 1), ('Orange', 1), ('Grape', 1), ('Banana', 1), ('Kiwi', 1)], [('Apple', 2), ('Orange', 2), ('Grape', 2), ('Banana', 2), ('Kiwi', 2)], [('Apple', 3), ('Orange', 3), ('Grape', 3), ('Banana', 3), ('Kiwi', 3)], [('Apple', 4), ('Orange', 4), ('Grape', 4), ('Banana', 4), ('Kiwi', 4)], [('Apple', 5), ('Orange', 5), ('Grape', 5), ('Banana', 5), ('Kiwi', 5)]]
[('Apple', 1), ('Apple', 2), ('Apple', 3), ('Apple', 4), ('Apple', 5), ('Orange', 1), ('Orange', 2), ('Orange', 3), ('Orange', 4), ('Orange', 5), ('Grape', 1), ('Grape', 2), ('Grape', 3), ('Grape', 4), ('Grape', 5), ('Banana', 1), ('Banana', 2), ('Banana', 3), ('Banana', 4), ('Banana', 5), ('Kiwi', 1), ('Kiwi', 2), ('Kiwi', 3), ('Kiwi', 4), ('Kiwi', 5)]
String Data
You can also use this Python list comprehension on string data. Here, we extract each character from a string and create a new one. In this example, we declared the string value as Tutorial Gateway.
string = 'Tutorial Gateway' print(string) my = [word for word in string] print(my) # Same using For loop print() new1 = [] for word in string: new1.append(word) print(new1)
Tutorial Gateway
['T', 'u', 't', 'o', 'r', 'i', 'a', 'l', ' ', 'G', 'a', 't', 'e', 'w', 'a', 'y']
['T', 'u', 't', 'o', 'r', 'i', 'a', 'l', ' ', 'G', 'a', 't', 'e', 'w', 'a', 'y']
Python List Comprehensions Vs Lambda Function
If fewer code lines are our priority, then we are not limited to this. You can use the lambda function. Here, we use the traditional approach and lambda function to multiply each item by itself.
By seeing the code, you can see that the lambda function is also very useful. However, the code is easy to read and execute faster.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = [] for num in numbers: a.append(num * num) print(a) print() b = [num * num for num in numbers] print(b) print() c = list(map(lambda num: num * num, numbers)) print(c)
Python List comprehensions vs lambda function final output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
It is another example of differentiating the code readability between this and lambda functions.
numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] doubleN = [num * 2 for num in numbers] print(doubleN) tripleN = [num * 3 for num in numbers] print(tripleN) squareN = [num ** 2 for num in numbers] print(squareN) #Lambda Function Example print("===================") dN = list(map(lambda num: num * 2, numbers)) print(dN) tN = list(map(lambda num: num * 3, numbers)) print(tN) sN = list(map(lambda num: num ** 2, numbers)) print(sN)
[20, 40, 60, 80, 100, 120, 140, 160, 180, 200]
[30, 60, 90, 120, 150, 180, 210, 240, 270, 300]
[100, 400, 900, 1600, 2500, 3600, 4900, 6400, 8100, 10000]
===================
[20, 40, 60, 80, 100, 120, 140, 160, 180, 200]
[30, 60, 90, 120, 150, 180, 210, 240, 270, 300]
[100, 400, 900, 1600, 2500, 3600, 4900, 6400, 8100, 10000]