Python Tutorial Python Advanced Python References Python Libraries

Python - List Comprehension

List Comprehension

List comprehension is a technique of creating new lists using other iterable and in fewer lines of codes. The iterable object which can be used in this technique can be any data structure like list, tuple, set, string and dictionary, etc. An iterable created by using range() function can also be used here.

The syntax used in list comprehension generally contains three segments:

  • iterable: iterable object like list, tuple, set, string, dictionary, etc.
  • transformation function: a transformation function that needs to be applied to the iterable.
  • filters: filters/conditions which are required to apply on iterable.


#list comprehension syntax
list = [tranform_func(i) for i in iterable if filters]

#which is equivalent to...
for i in iterator:
  if filters:

Example: List comprehension using various iterable

Below example describes how to apply different transformation functions on a given iterable.

#creating list of squares of natural numbers
MyRange = range(1,6)
NewList = [i*i for i in MyRange]

#creating list of odd numbers
MyTuple = (1, 2, 3, 4, 5, 6, 7, 8)
NewList = [i for i in MyTuple if i%2!=0]

#creating list of lists
MyList = [1, 2, 3, 4, 5]
NewList = [[i, i*i, i*i*i] for i in MyList]

#creating list of characters (in uppercase) of a string 
MyString = 'Hello'
NewList = [i.upper() for i in MyString]

#creating a list containing element length of a set
MySet= ('marry', 'john', 'sam', 'jo')
NewList = [len(i) for i in MySet]

The output of the above code will be:

[1, 4, 9, 16, 25]
[1, 3, 5, 7]
[[1, 1, 1], [2, 4, 8], [3, 9, 27], [4, 16, 64], [5, 25, 125]]
['H', 'E', 'L', 'L', 'O']
[5, 4, 3, 2]

Example: Find standard deviation using List Comprehension

List Comprehension technique can be leveraged to find out standard deviation of all elements of the list. Please see the example below:

MyList = [1,2,3,4,5]
mean = sum(MyList)/len(MyList)
stddev = sum([((i - mean)**2/len(MyList))**0.5 for i in MyList])

The above code will give the following output:


List Comprehension and transformation function

In above examples, transformation function is defined inside the list comprehension syntax. Alternatively, it can be defined outside of it, which gives the user to create more innovative function.

Example: Create Grades using List Comprehension

In the example below, a function called grade() is created which is used inside list comprehension syntax to categorize iterator's element.

def grade(x):
  if x < 0:
    return 'Invalid'
  elif x >= 0  and x < 30:
    return 'Fail'
  elif x >= 30  and x < 50:
    return 'Grade C'
  elif x >= 50  and x < 75:
    return 'Grade B'
  elif x >= 75  and x <= 100:
    return 'Grade A'
    return 'Invalid'

MyList = [20, 45, 67, 90, -1, 89, 102]
NewList = [grade(i) for i in MyList]

The above code will give the following output:

['Fail', 'Grade C', 'Grade B', 'Grade A', 'Invalid', 'Grade A', 'Invalid']

Example: Find Prime Numbers using List Comprehension

A function called prime is created which is further applied on iterator using list comprehension technique to find out prime elements of the iterator. Please see the example below for more details.

def prime(x):
  i = 2
  if x >= 2: 
    count = 0 
    count = None
  while i <= x-1:
    if x%i==0:
      count = 1
    i = i + 1
  if count == 0:
    return x

MyRange = range(1,20)
NewList = [prime(i) for i in MyRange if prime(i) is not None]

The above code will give the following output:

[2, 3, 5, 7, 11, 13, 17, 19]

❮ Python - Lists