List Comprehension in Python
Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known as List Comprehension. To achieve the required result, it follows the form of the mathematical set-builder notation, this form is different from the filter and map functions.
In Python, the expressions are contained in brackets and all these come under the domain of Python list comprehension. For creating a new list based on the values ofthe previously existing list, a Python list comprehension provides shorter syntax.
Advantages of using a list comprehension
- It is more efficient than loops, in both terms be it time efficiency or space efficiency.
- Being space efficient, it requires fewer lines of code.
- Since, it does not use loops, it simply converts them to formulas.
Syntax for List Comprehension:
name_of_list = [ element for element in previous_list if condition (if required)]
Examples of Python list comprehension
Example 1: Using iteration with list comprehension
# Using list comprehension to iterate through the loop
new_list=[ elementforelementin[1, 2, 3, 4, 5, 6, 7, 8]]
# Printing list using list comprehension
print(new_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
Example 2: Using list comprehension to print the list of even numbers
# Using list comprehension and using if-condition
new_list=[eleforeleinrange(11) ifele%2==0]
# Printing list using list comprehension
print(new_list)
Output:
[0, 2, 4, 6, 8, 10]
Example 3: Using list comprehension to print a matrix
mtrx=[[yforyinrange(4)] forxinrange(4 )]
# Printing a matrix created using the list comprehension
print(mtrx)
Output:
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
For loop vs. List Comprehension
There are different methods that we can use to iterate through a list. First, let us have a look at the “for loop” for iterating a loop.
Example:
# Creating an empty list
lst=[]
# Traditional approach of iterating
foriin'Java T Point':
lst.append(i)
# Returning an appended list
print(lst)
Output:
['J', 'a', 'v', 'a', '', 'T', '', 'P', 'o', 'i', 'n', 't']
The above-given approach is traditional to iterate over a list, tuple, string, etc. List comprehension also does a similar task but in an easier way and makes the code smaller too.
This method first converts the traditional approach for iteration to a simple formula, therefore making it easy to use. It converts multi-line code used for looping to a single-line formula.
Example of a list comprehension to iterate over a tuple, list, string, etc.:
# Using list comprehension to iterate through the loop
new_list=[ elementforelementin'Java T Point'
# Printing list using list comprehension
print(new_list)
Output:
['J', 'a', 'v', 'a', '', 'T', '', 'P', 'o', 'i', 'n', 't']
Time analysis in Loop and List Comprehension
As discussed earlier, list comprehension is time and space efficient, i.e., it takes less time and space as compared to the traditional looping method. Normally, they are written on a single line.
Example:
# Import time module, as it will be required to check the time
#taken by these two methods
importtimeas tm
# Defining the function to implement the for loop
defforLp(n):
rslt=[]
forxinrange(n):
rslt.append( x**2)
returnrslt
# Defining the function to implement thelist comprehension
deflst_cmp(n):
return[a**2forainrange(n)]
# Driver code to call functions created
# Calculating the time taken by theforloop()
start=tm.tm()
forLp(10**6)
end =tm.tm()
# Printing the time taken by the forloop()
print('Time taken by the for loop:', round(end-start, 2))
print('\n')
# Calculating the time taken by the list comprehension
start=tm.tm()
lst_cmpre(10**6)
end =tm.tm()
# Displaying the time taken by the list comprehension
print('Time taken by the list comprehension:', round(end-start, 2))
Output:
Time taken by the for loop: 0.27
Time taken by the list comprehension: 0.25
After observing the output of the above code, we can see that list comprehension is quite faster than loops.
Nesting in List Comprehensions
Nested list comprehensions are just like nested loops, when a list comprehension is within another list comprehension, it is said to be nested list comprehension. Below are two examples to show nested loops and nested list comprehension:
Example 1:
matrixx=[]
forxinrange(4):
# Append an empty sublist inside the list
matrixx.append([])
foryinrange(4):
matrixx[x].append( y )
print(matrixx)
Output:
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
Example 2:
# Nested list comprehension
matrix =[[j forj inrange(4)] foriinrange(4)]
print(matrix)
Output:
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
Lambda and List Comprehensions
Lambda functions are also like list comprehensions, they too help in making the code shorter. When list comprehensions are used with lambda functions, it forms an efficient combination.
Below are the examples for showing the use of lambda functions, and list comprehension for printing a table of 10:
Example 1: Printing a table of 10 using iteration
# Using iteration to print table
table=[]
forainrange(1, 11):
table.append( a*10)
print( table)
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Example 2: Printing a table of 10 using the list comprehension only
table=[a*10forainrange(1, 11)]
print( table)
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Example 3: Printing a table of 10 using a combination of lambda and list comprehension
# Using combination to print a table of 10
table=list(map(lambdaa: a*10, [aforainrange(1, 11)]))
print( table)
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Conditionals in List Comprehension
The conditional statements can also be used with list comprehension, by doing this we can create a list with the help of range( ), operators, etc.,and also apply required conditions using the else-if statements.
Key Points
- List Comprehension is one of the most efficientways to construct and describe lists based on existing lists.
- List Comprehension results in a simpler and more lightweightas compared to the standard loops and functions used to create lists.
- Using List Comprehensions results in short code, which makes the code more user-friendly.
- You can easily rewrite the list comprehension using the forloop. But it is not possible to rewrite the for loop in the context of List Comprehension
Following are the examples showing the use of list comprehension in multiple fields
Example 1: Using If-else for list comprehension in Python
list=["Even no"ifa%2==0
else"Odd no"forainrange(8)]
print(list)
Output:
[‘Even no’, ‘Odd no’, ‘Even no’, ‘Odd no’, ‘Even no’, ‘Odd no’, ‘Even no’, ‘Odd no’]
Example 2: Using nested if for list comprehension in Python
list=[aforainrange(100)
ifa%5==0ifa%10==0]
print(list)
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90]
Example 3: Printing square of numbers from 1 to 15
# Using list comprehension to get squares of numbers from 1 to 15
sq=[n**2forn inrange(1, 16)]
# Printingsquares of numbers from 1 to 15
print(sq)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225]
Example 4: Transposing a 2-D matrix
# Creating a matrix
mat =[[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# Transposing matrix
mat_tr=[[x[y] forxinmat] foryinrange(len(mat[0]))]
print(mat_tr)
Output:
[[10, 40, 70], [20, 50, 80], [30, 60, 90]]
Example 5: Converting the case of every character in the string
# Creating a string
str ='Java T Point'
# Toggle case of each character
lst=list(map(lambdaa: chr(ord(a) ^ 32), str))
# Printing converted list
print(lst)
Output:
[‘j’, ‘A’, ‘V’, ‘A’, ‘\x00’, ‘t’, ‘\x00’, ‘p’, ‘O’, ‘I’, ‘N’, ‘T’]
Example 6: Returning the sum of all odd elements present in a list
# Explicit function
defoddSum(n):
sum=0
foriinstr(n):
sum =sum+int(i)
returnsum
# Creating a list
lst=[36, 11, 56, 94, 67, 87]
# Using the function on odd elements of the list
Nw_lst=[oddSum(i) foriinlstifi&1]
# Returning a new list
print(nw_lst)
Output:
[2, 13, 15]