Python List Comprehension


Gaming Laptop Series

A python list can hold multiple different types of values in a single variable. In our previous article on Python list data type, we had discussed the Python lists, how to create them, and different operations that can be performed on them.

Python list comprehension provides a shorter syntax to create lists. In this article, you will learn Python list comprehension and how to use it.

How to create a Python list: a shorter way

You can create a Python list using list comprehension in the given way.

list_var=[x for x in iterable]

Where list_var is the list variable, item x will get appended to list_var every time for loop iterate over iterable. Now see some of the examples that are given below.

Example of Python list using list comprehension

In our example, we will create a list that will contain each letter of the string ‘explorelinux’ first we will see the normal way in which a Python list is created and then we will create the same list using list comprehension.

str_letters=[]
for x in 'explorelinux':
     str_letters.append(x)
print(str_letters)

Using list comprehension:

Using list comprehension you can reduce the number of lines of code. You can write the same code as given below

str_letters=[x for x in 'explorelinux']
print(str_letters)

Now see the output in the given image –

Using conditional statements in list comprehension

You can use conditional statements in list comprehension to modify the output on the basis of a condition. We will understand this with the help of an example.

We will create a list of even numbers ranging from 1 to 15 using list comprehension.

even_num=[x for x in range(1,16) if x%2==0]
print (even_num)

You can see the output below –

Using nested loop in list comprehension

A loop inside a loop is known as a nested loop. Suppose you want to create a matrix which is given below.

i.e. matrix =[[0,2,4],
             [0,2,4],
             [0,2,4]]

to create this we need two loops, see the code below-

matrix = [[j*2 for j in range(3)] for i in range(3)]
print(matrix)

You can see the ouput in the given image –

Conclusion

Now you know how to use list comprehension. If you have any query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.