List Comprehension in Python – Explained with Examples

In this post we will learn about the basic of list data-type in python, creating list in python and list comprehension.


List in Python:

List is a changeable and sequenced data type which allows it to be indexed and sliced. Lists are containers used to store heterogeneous values such as integers, floats, strings, tuples, lists, and dictionaries. In python programming, lists are commonly used to store collections of homogeneous objects. A list is an iterable object meaning it can return it’s one element at a time.

There are several ways to create a new list. The simplest one is to enclose the elements in square brackets[ ].

#enclose in square brackets[]

list1=[] #empty list

list2=['a','b','abc'] #homogeneous list

list3=[[1,2,3],[1,2,3,4],[10,20,30,40,50,60,70]] #nested list

list4=['abc',1,0,4,6,[1,2,3,6,8,9]] #heterogeneous list

Type conversion can also be used to create a list. Many built-in methods performs its processes and produces a list as result like String has a split method that separates a string by a character(by default white spaces) and produces a list of those separated substrings.

#Type Conversion 



st="This String will use split method"

Creating a list by writing down all of its elements is tiresome. This process can easily be automated by using loops. If the elements of a list follow a certain sequence then it will best to use loops to create that list rather than above methods. For example, a list of first ten whole numbers.

Using loops list can be created by following three steps:

1)Create an empty list

2)Loop over an iterable or range of elements.

3)Append each element in the list

Using While loops:
#list of first 10 natural numbers
while i<=10:

The same result can be achieved using range() function.

#List of first 10 even numbers

#List of even numbers between 1 to 100

#List of multiples of 5 lesser than 100

Range() function returns an immutable sequence of numbers between a specified range. It is used when an action needs to be performed for a specific number of times.  Range() mainly takes three arguments, first one is from where the range will begin, the second one is the ending integer of the series and the last one is the difference will be between one number and the next. By default, the starting integer is 0 and the default difference is 1.

Using for loop, we can iterate over a sequence of numbers produced by the range() function. The range() function uses the generator to produce numbers within a range, i.e., it doesn’t produce all numbers at once. It generates the next value only when for loop iteration asked for it.

#list of square of first five n numbers
for i in range(1,6):

List Comprehension

List comprehension is a compact method used to create a list using loops. This method defines a list and its contents at the same time.  Rather than creating an empty list and appending each element, list comprehension method can be used. This method increases the speed of execution. The basic syntax of list comprehension consists of a square bracket with an expression that is executed for each element along with for loop to iterate over each element.

new_list = [ expression for element in iterable ]

It can be simplified for future remembrance, by keeping in mind that the right-hand side of comprehension looks exactly like normal for loops while the left-hand side of comprehension is the expression of loop whose result is to be stored in the list.

#list of square of first 50 natural numbers
list1 = [ x**2 for x in range(1,51) ]

#list of cube of odd numbers between 100 to 200
list2 = [ v**3 for v in range(101,200,2) ]

#list of uppercase characters from a string
str1= "List Comprehension in Python"
list3 = [ ch.upper() for ch in s ]

#list of length of string in another list
list4 = [ len(str) for str in str_list ]

#list of celsius values in a list to farenheit
f_list = [ (float(c)*1.8)+32.0 for c in c_list ]

#Creating a 7 x 7 matrix using a list of lists
matrix = [[col for col in range(7)] for row in range(7)]

To make this method absolute conditional logic can be added to the comprehension. Conditionals are important because they filter out unwanted values by testing a suitable valid expression. If conditional can be added at the end of the syntax:

new_list = [ expression for element in iterable if conditional ]

#list of all the vowels present in a sentence
s='List comprehension is a compact method. It used to create a list using loops.'
v_list = [ ch for ch in s if s.lower() in 'aeiou' ]

#list of each character except space
s="Python is an easy language"
list1 = [ w for w in s if w != " " ]

#list of multiples of 2 which are not multiples of 3 lesser than 40
list2 = [ no for no in range(2,40,2) if no%3!=0 ]

If if-else is used in list comprehension then it should come before for loop in syntax:

new_list = [ expression if condition else expression for element in iterable ]

#list of characters in a word, replacing non vowels with 'X'
sen="Conditionals are important because they filter outs unwanted values by testing a suitable valid expression."
list1 = [x if x.lower() in 'aeiou' else 'X' for x in sen.split()]

#list of positive numbers and 0 replaced as negative number from another list
list3 = [ no if no > 0 else 0 for no in list2 ]

List comprehension can also be used to filter a list.

#list of positive non-zero numbers which are cubes of list 
list3 = [ v**3 for v in n_list if v**3 > 0 ]

#list containing elements having a specific substring
list4 = [ w for w in s_list if 'sa' in w ]

List comprehension can be used to combine several lists and create a list of lists.

nums = [1, 2, 3, 4, 5]
al= ['A', 'B', 'C', 'D', 'E']
nums_letters = [[no, l] for no in nums for l in al]

Apart from list comprehension, python also provides tools like Set comprehension and Dictionary comprehension.

Set Comprehension

Sets are unique and unordered collection of data enclose in curly bracket{}. A set in python represents a mathematical notion of set. Set comprehension is just like list comprehension, just instead of list it creates sets, and instead of square bracket it has curly brackets{}.

#set of even numbers between 1 and 10:
set1={x for x in range(2, 11,2)}

#Unique alphabetic characters in a string of text:
s="Sets are unique and unordered collection of data enclose in curly bracket{}."
set2={ch.lower() for ch in s if ch.isalpha()}

#set of cube of unique odd elements of a list
set3={ no**3 for no in n_list if no%2 != 0 }

Dictionary Comprehension

Dictionary is an unordered collection of unique_key : value pair enclose in curly bracket. Values in a dictionary can be of any datatype, mutable and can be duplicated, whereas keys can’t be repeated and are immutable. Dictionary comprehension is similar to set comprehension with an additional requirement of defining a key. In the comprehension expression key and values are separated by a colon ‘:’.

#Dictionary having keys lesser than 11 and values as keys's cube
cubes_dict = {i: i**3 for i in range(11)}

#dictionary containing index:upper_case_alphabet pair
dict_uc = {x:chr(64+x) for x in range(1, 27)}

#dictionary containing index:lower_case_alphabet pair
dict_lc = {x:chr(96+x) for x in range(1, 27)}
#merging two dictionaries using dictionary comprehension
dict1 = {'w': 1, 'x': 1}
dict2 = {'x': 2, 'y': 2, 'z': 2}
dict={k: v for d in [dict1, dict2] for k, v in d.items()}

Suggested Readings –


Tags: list comprehension, creating list, creating list using loops, list type conversion, Python, python list, range function, split method, types of list, filter using list comprehension, set comprehension, dictionary comprehension, combining several lists using list comprehension, Set in python, Dictionary in python

Leave a Comment

%d bloggers like this: