Progress

# Nested List Comprehension in Python: If-else, loop Examples The beauty of python lies in its simplicity and solving complex problems in less code. List comprehension is one of the most interesting features of python which allows you to write more logical and pythonic code.

My first encounter with list comprehension in python was on hacker earth website while solving a problem. At first, it was very confusing but after a few days, it was all good.

## What is List Comprehension in Python

List comprehension is a way to write logic inside a python list that perform a certain task. They are a beautiful way to create lists in python.

General use of list compression in Python is to create a new list with an iterable base on some condition or logic.

Here is a quick example to get all even numbers from a list using list comprehension.

Copy
``````a = [2,3,5,9,15,17,20,22]

evenItems = [i for i in a if i%2==0]

print(evenItems) #[2,20,22]``````

## Why use Python List Comprehension

Flat is better than nested.

Python Zen

List comprehension in python is a very elegant way to write logical code in short that create a specific list.

Let’s assume we have to do some super easy task of creating a list and initialize it with numbers 0 to 9. Then this will be our general approach.

Copy
``````numList = []
for i in range(10):
numList.append(i)``````

It took three lines of code for that simple task.

What if we can do it one line and focus on other complex parts of our code, here is the magic.

Copy
``numList = [i for i in range(10)]``

So simple as it seems.

## Types of list comprehension

There are various types of list comprehension which are used as per the problem. All types of list comprehensions are explained in detail with examples.

### For loop list comprehension

It is possible to use a ‘for loop’ inside list comprehension in python.

This is the general syntax of ‘for loop’ inside list comprehension in python

Copy
``newList = [ITEM for ITEM in ITERABLE]``

For example, if we want to double each item in any list then we will write it as:

Copy
``````oldList = [3,5,7]
newList = [i*2 for i in oldList]
#newList = [6,10,14]``````

See how simple and useful list comprehension is.

### Nested For loop List Comprehension

We frequently need to use nested loops to do certain operations, list comprehension provides an elegant way to write nested loops.

We can take an example where we want to pair each element of two lists then the general solution will be like this:

Copy
``````list1 = [1,2]
list2 = [4,5]

combinedList = []
for i in list1:
for j in list2:
combinedList.append(tuple((i,j)))

print(combinedList) #[(1, 4), (1, 5), (2, 4), (2, 5)]``````

But we can use list comprehensions to do this in one line.

Copy
``````list1 = [1,2]
list2 = [4,5]
combinedList = [(i,j) for i in list1 for j in list2]
print(combinedList)``````
Output
`[(1, 4), (1, 5), (2, 4), (2, 5)]`

If we see the general form of list comprehensions then it will be:

Copy
``[i,j,k for i in ITERABLE1 for j in ITERABLE2 for k in ITERABLE3 ......(and so on)]``

### If-else List Comprehension in Python

It is the most used type of list comprehensions in python where we can create a list from an iterable based on some condition.

It is most commonly used to for loop inside list comprehensions.

An example for if-else inside list comprehensions will be to find even and odd numbers in any list.

Copy
``````some_list = [1,4,7,12,19,22, 23, 26]
new_list = ["{} is even".format(i) if(i%2==0) else "{} It is odd".format(i) for i in some_list]
print(new_list)``````
Output
`['1 It is odd', '4 is even', '7 It is odd', '12 is even', '19 It is odd', '22 is even', '23 It is odd', '26 is even']`

### Nested List Comprehensions

It is possible to use list comprehensions in the nested list of another list.

Example to transpose rows and columns of a matrix with the use of nested list comprehensions in Python.

Copy
``````someMatrix = [
[3, 5, 1, 6],
[1, 0, 9, 5],
[4, 14, 22, 17],
]
transpose = [[row[i] for row in someMatrix] for i in range(len(someMatrix))]
print(transpose) # [[3, 1, 4], [5, 0, 14], [1, 9, 22], [6, 5, 17]]``````

The logic of the above list comprehension is similar to the following code.

Copy
``````transpose = []
for i in range(4):
# The next 3 lines are for nested list compression
transpose_row = []
for row in someMatrix:
transpose_row.append(row[i])
transpose.append(transpose_row)
print(transpose)
``````

## When to avoid the use of List comprehensions?

Feeling excited to use list comprehensions everywhere in your code? Wait one second.

Using too much List comprehension in python will make your code unreadable.

Yes, list comprehension is very useful to write more beautiful and pythonic code. It is always recommended to use list comprehension in Python but maintain the code readability.

If you use list comprehension for a very complex problem then it will be a nightmare for other developers to read your code.

Always remember one thing, what you know about your code others will take time to understand it. So as responsible developers we need to write code that others can read without a problem.

You can use list comprehensions freely in the code which is not for human reading like in programming exams (that’s where I use it most).

## Conclusion

It seems very cool to use list Comprehensions everywhere. But it has its own cost.

List comprehension makes the code hard to understand, it is always recommended to avoid list compression in complex cases.

As a responsible developer, we should comment the code properly where we use list compression because it will help others to easily understand the code.

You can freely use list compression where you don’t expect humans to read the code or you want the code reader to focus on other parts of code other than that (compressed).

If you have any problem, suggestions and examples then feel free to share them in comments.

Share the Post ;)

Related Posts