Loop Control Statements in C Introduction to HTML How to use the Github API The image tag, anchor tag and the button tag Ordered and Unordered Lists in HTML The division tag HTML Forms Tables in HTML Introduction to C Programming Introduction to Python Varibles and Datatypes in Python Operators in Python Typecasting in Python Input and Output in Python If Else in Python Loops in Python Break, Continue and Pass in Python Python practice section 1 Lists in Python Tuple in Python

List Comprehension in Python

It provides a short syntax to create new lists. Normally, we create lists like this -

list1=[]
for i in range(1,6):
list1.append(i)

print(list1)
    
Output
[1, 2, 3, 4, 5]
    
Using List Comprehension, we can create new lists in just 1 line of code.

list2=[i for i in range(1,6)]
print(list2)
    
Output
[1, 2, 3, 4, 5]
        
A variety of lists can be created in this way.

m=[1 for i in range(1,6)]
print(list3)

print()

n=[i for i in "Rapid"]
print(list4)
    
Output
[1, 1, 1, 1, 1]

['R', 'a', 'p', 'i', 'd']
        
We can also use if-else statements in list Comprehension.

list5=[i for i in range(1,10) if i%3==0 ]
print(list5)

print()

mylist=["Rapid", "Coders", "Excellent", "Coders"]

list6=[i if i != "Excellent" else "Good" for i in mylist ]

print(list6)
Output
[3, 6, 9]

['Rapid', 'Coders', 'Good', 'Coders']

Nested List Comprehension

Suppose that you want to create a nested list with numbers from 1 to 5 in every list. In one line, you can do it like this -

list7=[[i for i in range(1,6)] for j in range(1,6)]
print(list7)
    
Output
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]   
    
Now, suppose you want to flatten the above list. You can do it like -

list8=[i for j in list7 for i in j]
print(list8)
    
Output
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
    
Suppose you want to get the tables of all numbers from 2 to 5. You can do it like -

tables=[[i*j for i in range(1,11)] for j in range(2,6)]

for table in tables:
    print(table)
    
Output
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
[4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
    

Advantages of List Comprehension

  1. It is easy to use.
  2. Reduces lines of code.
  3. Easy to understand.
Please note that every list cannot be created using List Comprehension.