List Comprehensions in Python

FREE Online Courses: Transform Your Career – Enroll for Free!

You would have heard of lists as a collection of values of different data types, including lists. Wondering if these list comprehensions are again another data type?

Then the answer is no! List comprehensions are a way to work on the lists using a short and efficient code. To dig deeper into these concepts, let’s start.

Lists in Python

As said above lists are stores of elements of different data types, where the values are stored in a contiguous manner in the memory. These can store integers, floats, strings, lists, tuples, etc.

Creating a Python list

To create a list we enclose the elements in square brackets and separate them by a comma. We can check the data type using the type() function.

Example of creating a list:

list1=[1,'a',5.6,'Python']
print("The data type of",list1,"is:",type(list1))

Output:

The data type of [1, ‘a’, 5.6, ‘Python’] is: <class ‘list’>

Accessing elements of Python List

To access the elements of a list we use the index, where the indexing starts from 0. We can also give negative indexing. The rightmost value has -1 as the index and it reduces as we go to the left. To access multiple values between the indexes i and j (j excluded), we use the argument as ‘i:j’. Here, the value of i and j can be missing based on the condition.

Example of accessing element(s) of a list in Python:

print(list1) #printing the entire list

print(list1[1]) # accessing the 2nd element

print(list1[-1]) # accessing the last element

print(list1[1:4]) # accessing the 2nd to 4th elements

print(list1[-4:-1]) # accessing the last 4th to last 2nd element

print(list1[:2]) # accessing the elements till 3rd one

print(list1[-3:]) # accessing the elements from last 3rd one

Output:

[1, ‘a’, 5.6, ‘Python’]

a

Python

[‘a’, 5.6, ‘Python’]

[1, ‘a’, 5.6]

[1, ‘a’]

[‘a’, 5.6, ‘Python’]

There are many other properties and methods that can be applied on lists. But let us concentrate on that one property which is most important to discuss further on list comprehensions. This is to iterate through the list. The most common way is to use the for loop as shown below.

Example of iterating through the Python list:

list1=[1,2,'a',5.6,7.8]
for ele in list1:
    print(ele)

Output:

1
2
a
5.6
7.8

Want to know how this concept is useful to understand list comprehensions? Then read the below section.

Python List comprehensions

List comprehensions are a shorter way to create a list from existing containers like lists, strings, etc. For example, if you have a list and want to create a new list by incrementing the values of the existing list by 2. Then we write the following code.

Example of creating a new list from the list:

list1=[3,5,19,7,23]
list2=[]
for i in list1:
    list2.append(i+2)

print(list2)

Output:

[5, 7, 21, 9, 25]

Using list comprehension you can do this operation in just one line. The syntax of the list comprehension is:

new_list=[expression for element in list]

The way to write the above code using list comprehension is shown below.

Example of creating a new list using list comprehension:

list1=[3,5,19,7,23]
list2=[i+2 for i in list1]
print(list2)

Output:

[5, 7, 21, 9, 25]

Here ‘i’ is the iterator used to go through each element of the list and enclosed in the square braces make the resultant list. This might be a small change in the lines of code, but as we have conditions and nested loops, we can see the difference.

Advantages of list comprehensions:

1. Efficiency in time and space complexity
2. Shorter lines of code
3. Transforming iteration into mathematical formulas

Let’s see another example where list comprehension is used on a string. LIst comprehension can identify the input if a string or list or tuple, etc., and work accordingly as it does for a string.

Example of creating a list from string using list comprehension:

string="PythonGeeks"
list3=[i for i in string]
print(list3)

Output:

[‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’]

Conditionals in list comprehensions in Python

We can also give conditionals to the list comprehensions and let the element add to the new list only if the condition is matched. Or do a specific operation if True and another if False. The syntax with the condition is :

newlist = [expression for element in iterable if condition == True]

For example, to create a new list if the values are divisible by 3.

Example of creating a list using conditionals in list comprehensions:

list1=[1,2,3,4,5,6]
list2=[ i for i in list1 if i%3==0]
print(list2)

Output:

[3, 6]

We can add nested conditions and if-else inside the list comprehensions.

1. Nested if conditions in Python

We can add more than one condition by adding the if statements one after another. For example, to add to the list only if the value is greater than -3 and less than 15, we can write the below code.

Example of creating a list using multiple conditionals in list comprehensions:

list1=[4,-6,3,19,34,0,-2,14]
list2=[i for i in list1 if i>-3 if i<15]
print(list2)

Output:

[4, 3, 0, -2, 14]

In this, the code first filters those values less than -3 and then checks the condition of i<15 for the remaining values. Finally, it keeps only those values from the filtered one that is less than 15.

2. If else conditions in Python

We can add if-else conditions to do different operations in different situations and add to the new list. The syntax is similar to the above cases, we have ‘else’ block following that of ‘if’, but at the beginning.

For example, the following code shows how to add an element if positive or negative by checking conditions, assuming no zeros.

Example of creating a list using if else conditionals in list comprehensions:

list1=[1,-12,34,-4,25,-16,19]
list2=["+ve" if i>0 else "-ve" for i in list1]
print(list2)

Output:

[‘+ve’, ‘-ve’, ‘+ve’, ‘-ve’, ‘+ve’, ‘-ve’, ‘+ve’]

List comprehensions for nested loops in Python

If we want to create a list that stores the sum of each element of the first list with that of the second list, then we use a nested loop as shown below.

Example of creating a list using nested loops

list1=[1,2,3,4]
list2=[7,8,9]
list3=[]
for i in list1:
    list4=[]
    for j in list2:
        list4.append(i+j)
    list3.append(list4)

  
print(list3)

Output:

[[8, 9, 10], [9, 10, 11], [10, 11, 12], [11, 12, 13]]

We can perform the same operation using list comprehensions in the following manner

Example of creating a list using nested loops

list5=[[i+j for i in list2] for j in list1]
print(list5)

Output:

[[8, 9, 10], [9, 10, 11], [10, 11, 12], [11, 12, 13]]

Expressions and functions in the Python list comprehensions

We can use expressions as an item for the iterator in the list comprehension. For example, if we want to add the small letters from the original list we can use the lower() function.

Example of creating a list with expression:

string='AbcDeFG'
list1=[i.upper() for i in string]
print(list1)

Output:

[‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’]

We can also add a built-in function such as isdigit(), isalnum(),etc for strings.

Example of using built-in functions in list comprehension:

string2="abc#123@4th"
list2=[i for i in string2 if i.isalnum()]
print(list2)

Output:

[‘a’, ‘b’, ‘c’, ‘1’, ‘2’, ‘3’, ‘4’, ‘t’, ‘h’]

We can also use a user defined function inside a list comprehension as shown in the below example.
Example of using function in a list with expression:

def abs(x):
    if(x>=0):
        return x
    else:
        return -x
list3=[1,-2,3,-4,5,-6,7]
list4=[abs(i) for i in list3]
print(list4)

Output:

[1, 2, 3, 4, 5, 6, 7]

List comprehension vs lambda function

A lambda function is a way of creating a function anonymously. This function is also written in a single line and can be applied to iterables. This function usually involves map(), filter(), and reduce() functions to operate on the iterables.

1. Alternate for map():

The basic syntax of using map() in lambda function is :

map(lambda x: expression(x),iterable)

An example of using lambda function to create a list from a tuple is :

Example of creating a list from tuple using lambda with map() function:

tup=(1,4,1.3,'a',7.9)
list1=list(map(lambda i:i,tup))
print("The data type of",list1,"is:",type(list1))

Output:

The data type of [1, 4, 1.3, ‘a’, 7.9] is: <class ‘list’>

Here, for each value of ‘i’ in the tuple, the ‘i’ is returned by mapping on the tuple. Then this mapping is converted to a list using the list() function. The below example shows the way do the same using list comprehension

Example of creating a list from tuple using list comprehension:

list2=[i for i in tup]
print("The data type of",list2,"is:",type(list2))

Output:

The data type of [1, 4, 1.3, ‘a’, 7.9] is: <class ‘list’>

Here, the usual syntax of the list comprehension discussed above is used.

2. Alternate for filter():

We use filter() function to keep the wanted values that satisfy the condition. The syntax of filter() in lambda function is :

filter (lambda x: condition(x),iterable)

For example to filter out the values that are not greater than 10

Example of creating a list using lambda with filter() function:

list1=list(range(5,19))
print(list1)

list2=list(filter(lambda i: i>10,list1))
print(list2)

Output:

[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

[11, 12, 13, 14, 15, 16, 17, 18]

Here, ‘i’ is mapped to the tuple, and for each value of ‘i’ in the tuple, the condition of ‘i<10 is checked for filtering. Then this mapping is converted to a list using the list() function and this list consist only of those values that are greater than 10.

The below example shows the way do the filtering using list comprehension

Example of filtering using list comprehension:

list3=list(range(5,19))
list4=[i for i in list3 if i>10]
print(list4)

Output:

[11, 12, 13, 14, 15, 16, 17, 18]

Here, the usual syntax of the list comprehension with the if conditional at the end is used , as discussed previously.

3. Alternate for reduce():

The function reduce() is used to combine the results of all the values of an iterable based on the expression given. The syntax of filter() in lambda function is :

reduce(lambda x: expression(x),iterable)

We need to import this function from the ‘functools’ module. For example, to find the maximum value of all the elements of a list, we can write the following code.

Example of creating a list using lambda with reduce() function:

from functools import reduce
list1=[-5,3,5,1,29,-34,3]
print(reduce(lambda x,y: x if x>y else y,list1))

Output:

29

Here, the following steps take place.

Process of Reducing in Lists Comprehensions in Python

The below example shows the way do the filtering using list comprehension

Example of reducing using list comprehension:

list2=[-5,3,5,1,29,-34,3]
print(max([i for i in list2]))

Output:

29

Here, the list is first created by list comprehension and the max() function used finds the maximum value.

We can see that the method of list comprehension is more readable and easier to understand by a programmer.

Interview Questions on Python Lists Comprehensions

It’s practice time! Let us see some questions on list comprehensions.

Q1. Write a single line program to store squares of all the numbers from 1 to 10 into another list.

Ans. We can write the list comprehension in Python as below:

list1=[i**2 for i in range(1,11)]
print(list1)

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Q2. Write a program to convert the values into integers and store in another list using list comprehension

Ans. Below is the example of converting the values into integers and store in another list using list comprehension

list1=[1.2,3.0,9.5,4,7.4]
list2=[int(x) for x in list1]
print(list2)

Output:

[1, 3, 9, 4, 7]

Q 3. Write a program to flatten a two dimensional list using list comprehension
Ans. Below is the example of flattening a 2D list using list comprehension:

list=[[1,3,4],[23,32,56,74],[-2,-6,-9]]
list2=[i for row in list for i in row]
print(list2)

Output:

[1, 3, 4, 23, 32, 56, 74, -2, -6, -9]

Q4. Write a function to find the cube of a value and use it inside a list comprehension. Add a condition of the value being even inside a list comprehension.

Ans. Below is the example of using function in list comprehension:

def cube(x):
    return x**3

list1=[1,2,3,4,5,6,7,8]
list2=[cube(i) for i in list1 if i%2==0]
print(list2)

Output:

[8, 64, 216, 512]

Q5. Write a list comprehension that checks if a character is a digit. If digit, convert it into integer and add, else add as a character.

Ans. Below is the example of using if else in Python list comprehension:

string="abC#168@ry7"
list1=[int(i) if i.isdigit() else i for i in string]
print(list1)

Output:

[‘a’, ‘b’, ‘C’, ‘#’, 1, 6, 8, ‘@’, ‘r’, ‘y’, 7]

Quiz on List Comprehensions in Python

Conclusion

In this article, we first revised lists in python. Then we learned about list comprehensions and their different properties using conditionals. After this, we compared it with the lambda function. Finally, we saw some interview questions.

It is a suggestion to make an optimal choice for your program that is easier to understand. It is completely based on the complexity of the problem. Hope you gained some knowledge from this write-up. Happy learning!

Did you like our efforts? If Yes, please give PythonGeeks 5 Stars on Google | Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *