List Comprehensions

Deepti Goyal
Analytics Vidhya
Published in
2 min readApr 7, 2020

A list comprehension allows you to generate this same list in just one line of code. A list comprehension combines the for loop and the creation of new elements into one line and automatically appends each new element.

Let’s start with an example —

How can we write the below code in one line —

list1 = []
for i in range(0,8):
list1.append(i**2)
print(list1)

The output is — [0, 1, 4, 9, 16, 25, 36, 49]

In the list comprehension as shown below — we will first start with what we want as output inside a list followed by the for loop condition.

list1 = [i**2 for i in range(0,8)]
print(list1)

If you run the above code you will get the same output.

If-else in List Comprehension

Example —(simple If condition): You want only the even numbers in your list

list1 = []
for i in range(0,8):
if (i%2==0):
list1.append(i)
print(list1)

How can we reduce this code to one line —

list1= [i for i in range(0,8) if (i%2==0)]
print(list1)

Both will give this as the output — [0, 2, 4, 6]

What if we have an if-else condition —

Example we want to square the even numbers and cube the odd numbers

Square — even number, cube — Odd numbers

How can we implement this using list comprehension-

Using list comprehension

Note: If there is only ‘if’ condition then write it after ‘for loop’ but if you have both ‘if-else’ condition then write it before the ‘for loop’( as shown above in the example)

Nested List Comprehension: —

I want to create a matrix which looks like below:

matrix = [[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5]]

Using list —

How can we implement the same code in one line using list comprehension —

Great :) we are done with list comprehension. Let me know if this explanation was helpful. For more such explanations on python topics please follow me.

My next blog will be on Dictionary comprehension.

My Github link:- https://github.com/DeeptiAgl?tab=repositories

--

--