List Comprehension in Python

  • List Comprehensions provide a concise way to create lists.
  • List Comprehension is generally used to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
  • A List Comprehension consists of brackets ( starts with a ‘[‘ and ‘]’ ) containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
  • Basic syntax is [ expression for item in list if conditional ]

If we remember Set-Builder Notation, for example { x : x > 0}, means, the set of all x’s, such that x is greater than 0 (any value greater than 0) and this representation can be written as {1,2,3,4,5,..}

Similarly with this Set-Builder Notation { x: x >=2 and x <= 6} can be written as { 2,3,4,5,6 }

Now, if we take {x ^ 2: x is a natural number less than 10 }, can be written in List Comphrehension as [x**2 for x in range(0,10)]. See the below code.

>>> [x**2 for x in range(0,10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Now let’s assume if we want to create a list of cubes using for loop, like:

>>> cubes = []
>>> for x in range(5):
...     cubes.append(x**3)
...
>>> cubes
[0, 1, 8, 27, 64]

In the above program it created variable named “x” that still exists after the loop completes. The same can be done using List Comphrehension with more concise and readable without any side effects as below…

>>> [x**3 for x in range(0,5)]
[0, 1, 8, 27, 64]

Let us see some more List Comphrehension examples

# Create a new list with the values doubled
>>> myList = [1,2,3,4,5]
>>> [x*2 for x in myList]
[2, 4, 6, 8, 10]

# Apply a function to all the elements
>>> import math
>>> myList = [1,2,3,4,5]
>>> [math.sqrt(x) for x in myList]
[1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979]

>>> mySquareList = [1,4,9,16,25]
>>> [math.sqrt(x) for x in mySquareList]
[1.0, 2.0, 3.0, 4.0, 5.0]

>>> [x.upper() for x in ["girish",'a','e','i','o','u']]
['GIRISH', 'A', 'E', 'I', 'O', 'U']

>>> [x.lower() for x in ["GIRISH",'A','E','I','O','U']]
['girish', 'a', 'e', 'i', 'o', 'u']

# Filter the list with a if condition
>>> myList
[1, 2, 3, 4, 5]
>>> [x for x in myList if x >= 3]
[3, 4, 5]

>>> myList = [ x for x in range(10)]
>>> myList
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> myListEven = [ x for x in myList if x % 2 == 0]
>>> myListEven
[0, 2, 4, 6, 8]

# Multiple if Conditions
>>> [x for x in range(40) if x%2==0 if x%6==0]
[0, 6, 12, 18, 24, 30, 36]

# If Else Condition
>>> [x*2 if x >=5 else x*3 for x in range(11)]
[0, 3, 6, 9, 12, 10, 12, 14, 16, 18, 20]

# Create a list of 2-tuples like (number, cube)
>>> myList
[1, 2, 3, 4, 5]
>>> [(x,x**3) for x in myList]
[(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]

# Complex expressions and nested functions
>>> from math import pi
>>> [str(round(pi,x)) for x in range(1,8)]
['3.1', '3.14', '3.142', '3.1416', '3.14159', '3.141593', '3.1415927']

# Nested List comprehension transposing rows and columns
>>> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
>>> [[row[x] for row in matrix] for x in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

# zip() function for transposing rows and columns
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

# Multiplication Tables of 2 and 3 in the form of Nested Lists
>>> [[i*j for j in range(1,11)] for i in range(2,4)]
[[2, 4, 6, 8, 10, 12, 14, 16, 18, 20], [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]]

# Filtering Common Names from two Lists
>>> facultyList = ["Girish","Sanjay","Ramesh"]
>>> studentsList =["Gopal","Krishna","Girish","Sai","Sanjay"]
>>> filterCommonNames = [x for x in facultyList for y in studentsList if x == y]
>>> print(filterCommonNames)
['Girish', 'Sanjay']

References

  • https://docs.python.org

Learn more about Python Advanced features in the next Blog Articles.

Happy Learning!