Python List Comprehensions

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 Python 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)

Simple Python list comprehension output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

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. I suggest you refer to the Python List, for loop and Python List functions from Python page.

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)

Python List comprehension vs For loop Output

[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 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)

List Comprehension Vs For Loop output 2

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
===================
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

We are using the Python 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)

List Comprehension Multiplication output

[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 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)

List Comprehension Multiplication Output 2

[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 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 Comprehensions 6

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)

If statement in List comprehension output

[2, 4, 6, 8, 10]

[2, 4, 6, 8, 10]

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)

List comprehension with multiple conditions output

[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 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)

If else statement in List comprehension output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']

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}")

List comprehension vs Nested for loops output

[[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

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)

List comprehension to transpose a matrix output

[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
[[10, 40, 70], [20, 50, 80], [30, 60, 90]]

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)

List comprehension to convert nested list to normal output

[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
[10, 20, 30, 40, 50, 60, 70, 80, 90]

[10, 20, 30, 40, 50, 60, 70, 80, 90]

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 to add two lists and convert tuples to list

[[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)]]

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)

Using string functions in List comprehension output

['ApplE', 'OraNGe', 'GrAPe', 'BaNAna']
['apple', 'orange', 'grape', 'banana']
['APPLE', 'ORANGE', 'GRAPE', 'BANANA']

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)

List comprehension and string functions output

['ApplE', 'OraNGeS', 'GrAPe', 'BaNAna']
['aPPLe', 'oRAngEs', 'gRapE', 'bAnaNA']
[5, 7, 5, 6]
['A', 'O', 'G', 'B']

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)

Python Nested List comprehension output

[[('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)]

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)

List comprehension on a string output 1

Python
['P', 'y', 't', 'h', 'o', 'n']

['P', 'y', 't', 'h', 'o', 'n']

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)

Using List comprehension on a string output 2

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 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)

List comprehensions vs lambda function 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 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)

List comprehensions vs lambda function output 2.

[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]
[20, 40, 60, 80, 100, 120, 140, 160, 180, 200]
[20, 40, 60, 80, 100, 120, 140, 160, 180, 200]