Get The Most Affordable Hosting in the World!

Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.

Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!

Get Started Now!

List comprehension is a very powerful programming tool. It is similar to set builder notation in mathematics. It is a concise way to create new list by performing some kind of process on each item on existing list. List comprehension is considerably faster than processing a list by for loop.

Example 1

Suppose we want to separate each letter in a string and put all non-vowel letters in a list object. We can do it by a for loop as shown below −

 
chars=[] for ch in 'TutorialsPoint': if ch not in 'aeiou': chars.append(ch) print (chars)

The chars list object is displayed as follows −

['T', 't', 'r', 'l', 's', 'P', 'n', 't']

List Comprehension Technique

We can easily get the same result by a list comprehension technique. A general usage of list comprehension is as follows −

listObj = [x for x in iterable]

Applying this, chars list can be constructed by the following statement −

 
chars = [ char for char in 'TutorialsPoint' if char not in 'aeiou'] print (chars)

The chars list will be displayed as before −

['T', 't', 'r', 'l', 's', 'P', 'n', 't']

Example 2

The following example uses list comprehension to build a list of squares of numbers between 1 to 10

 
squares = [x*x for x in range(1,11)] print (squares)

The squares list object is −

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Nested Loops in List Comprehension

In the following example, all combinations of items from two lists in the form of a tuple are added in a third list object.

Example 3

 
list1=[1,2,3] list2=[4,5,6] CombLst=[(x,y) for x in list1 for y in list2] print (CombLst)

It will produce the following output −

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

Condition in List Comprehension

The following statement will create a list of all even numbers between 1 to 20.

Example 4

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

It will produce the following output −

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]



The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.
Kas see vastus oli kasulik? 1 Kasutajad peavad seda kasulikuks (1 Hääled)