Python List Comprehension

Python's List Comprehension enables us to work with list items easily.
List Comprehension is challenging for beginners but once you get used to it, you will use it every opportunity.
Given a function that requires us to create a list of x square for range(20). See below without list comprehension.

def getSquare():
	newList = []
	for x in range(20):
		newList.append(x * x)

This can be easily shorted via list comprehension as shown below.
newList = [x * x for x in range(20)]

As you can see using List comprehension significantly saves the number of lines of code. But you must take care. Overuse of List comprehension may compromise on readability of your code.

We can enhance a list comprehension using conditional statements as well. For instance, if we want to filter out a list with only even numbers / odd numbers, we can keep a conditional check as shown below.
>>> lst = range(10)
>>> even_nums = [i for i in lst if i % 2 == 0]
>>> even_nums
[0, 2, 4, 6, 8]

>>> lst = range(10)
>>> odd_nums = [i for i in lst if i % 2 == 1]
>>> odd_nums
[1, 3, 5, 7, 9]

We can also use list comprehension for nested loops. For example, consider a nested loop as shown below:
>>> for i in [1,2]:
        for j in [3,4]:

>>> newList
[4, 5, 5, 6]

We can express the same using list comprehension as shown below:
>>> [i+j for i in [1,2] for j in [3,4]]
[4, 5, 5, 6]

Previous: Python List | Next: Python Tuple


Share this page:

Report Error in Content