Python - List Comprehension



List Comprehension in Python

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 of Python List Comprehension

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']

Python 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

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 Python 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

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 Python List Comprehension

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

Example

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]
Advertisements