## What is List Comprehension?

According to the official documentation, list comprehension is a way to create lists in a more readable, concise manner in one line. A typical list comprehension syntax takes the form below. In the next sectional we’ll be looking at some examples to gain more insights into List comprehensions.

### Syntax:

[<expression> <for loop> <for loop>* <conditional statements>* ]
where * represents 0 or more.

### List comprehension as an alternative to a single for loop

Suppose if we have a list of integer elements and we want to increment all the elements by a scalar (say 2). We can use traditional for loop like this

``````nums = [1,3,5,8,9,10,12]
for i in range(len(nums)):
nums[i]+=2
print(nums)
print(i)``````

Output:

``````[3, 5, 7, 10, 11, 12, 14]
6``````

Above is the traditional approach but look at the output, we can even use the loop variable outside the scope of the loop. This might cause critical bugs in the program. Let’s see how we can use List comprehension to achieve the results.

``````nums = [1,3,5,8,9,10,12]
nums = [i+2 for i in nums]
print(nums)
print(i)``````

Output:

``````[3, 5, 7, 10, 11, 12, 14]
Traceback (most recent call last):
File "<string>", line 4, in <module>
NameError: name 'i' is not defined``````

After printing the desired results, it shows that name i is not defined since we are using list comprehension.

### List comprehension as an alternative to a single for loop with a single condition

Suppose we have the same list of integers as above and we want to print only odd element.

``````nums = [1,3,5,8,9,10,12]
odd=[]
for i in nums:
if i%2 != 0:
odd.append(i)
print(odd)``````

Output:

``[1, 3, 5, 9]``

For such a simple program we don’t want to create extra space for storing the results. Another way was to delete the element but one such missing statement can cause the whole program to behave unexpectedly. Let see how we can do this using the List comprehension provided in Python.

``````nums = [1,3,5,8,9,10,12]
nums = [i for i in nums if i%2!=0]
print(nums)``````

Output:

``[1, 3, 5, 9]``

### List comprehension as an alternative to a single for loop with multiple conditions

Multiple conditions can be tricky to understand in loop comprehension, for example, suppose we have a list of integers from 1 to 9 and we want to apply multiple conditions on it.

• Condition 1 – if the element is less than or equal to 3, then increment it by 2.
• Condition 2 – else if the element is less than or equal to 6, then increment it by 3.
• Otherwise – else increment the element by 4
Desired modification:
1 -> 3 inc by 2
2 -> 4
3 -> 5
4 -> 7 inc by 3
5 -> 8
6 -> 9
7 -> 11 inc by 4
8 -> 12
9 -> 13

Let see how we can achieve this by using traditional looping and conditional statements.

``````nums = [1,2,3,4,5,6,7,8,9]
for i in range(len(nums)):
if nums[i]<=3:
nums[i]+=2
elif nums[i]<=6:
nums[i]+=3
else:
nums[i]+=4
print(nums)``````

Output:

``[3, 4, 5, 7, 8, 9, 11, 12, 13]``

We see we have to write so many statements for the simple program. The list comprehension approach will make it too simple in one line. Let see the code by using list comprehension.

``````nums = [1,2,3,4,5,6,7,8,9]
nums = [x+2 if x<=3  else x+3 if x<=6 else x+4 for x in nums]
print(nums)``````

Output:

``[3, 4, 5, 7, 8, 9, 11, 12, 13]``

### List comprehension as an alternative to the multiple for loops

Let us create 2-D zero matrix (All elements are 0) to understand the concept of a list of lists. If we use the naive method we will require 2 for loops.

``````mat=[]
for i in range(3):
row = []
for j in range(3):
row.append(0)
mat.append(row)
print(mat)``````

Output:

``[[0, 0, 0], [0, 0, 0], [0, 0, 0]]``

That how we use a nested loop to create a 2-D Matrix. Using list comprehension we can achieve same results in a single line.

``````mat = [[0 for row in range(3)] for column in range(3)]
print(mat)``````

Output:

``[[0, 0, 0], [0, 0, 0], [0, 0, 0]]``

## Advantages of using List Comprehension

From all the examples we have discussed above we can see some of the advantages of using list comprehension over traditional approaches.

• Loop variable cannot be used outside the scope of the loop.
• More secure and secure.
• Faster than most of the naive approach.

So in this tutorial, we see how we can use list comprehension to make our code more compact, readable and concise and ended with some of the advantages that list comprehensions provide to us.

## Resources

Happy Learning 🙂

### About the Author: Kunal Gupta Aspiring Data Scientist who loves Python Programming, Software Development and wants to Solve Real-world Problems.