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.

Syntax

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

#which is equivalent to...
for i in iterator:
  if filters:
    list.append(tranform_func(i))

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]
print(NewList)

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

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

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

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

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. 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])
print(stddev)

The above code will give the following output:

2.6832815729997477

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'
  else:
    return 'Invalid'

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

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. See the example below for more details:

def prime(x):
  i = 2
  if x >= 2: 
    count = 0 
  else: 
    count = None
  while i <= x-1:
    if x%i==0:
      count = 1
      break
    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]
print(NewList)

The above code will give the following output:

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

❮ Python - Lists