One of Python’s most distinctive features is its ability to produce substantial functionality in just one line of code by using list comprehension. However, many programmers find it challenging to fully take advantage of Python’s more complex list comprehension features. Some programmers might even misuse them, which would make the code harder to read and less productive.
You’ll be able to utilize list comprehension when it makes sense and learn how to write cleaner, more elegant code once you’ve finished reading this tutorial. Additionally, you’ll comprehend the trade-offs associated with applying them so that you may decide when other strategies are more advantageous.
Syntax of list comprehension
Instead of starting with an empty list and appending each item one at a time, use the following syntax to define both the list and its components simultaneously:
list_comprehension = [variable_name for x in name_iterable] |
- variable_name = It is the output value
- x = is the value in the list or the Iterable.
- name_iter = can be a list, string, dictionary, or any other object that can iteratively deliver each element one by one time.
# printing out each letter in a text using list comprehension format a = [x for x in ‘list comprehension’] print(a)  OUTPUT: [‘l’, ‘i’, ‘s’, ‘t’, ‘ ‘, ‘c’, ‘o’, ‘m’, ‘p’, ‘r’, ‘e’, ‘h’, ‘e’, ‘n’, ‘s’, ‘i’, ‘o’, ‘n’] |
Conditions in List Comprehension
Now the conditions will be used while writing the list comprehension code. As we know that the conditions in python are written with the help of an if-else statement.
# using list comprehension to print all the numbers divisible with 2,4,5 within [0,50] c = [i for i in range(50) if i % 2==0 if i % 4 == 0 if i % 5 == 0] print(c) OUTPUT: [0, 20, 40] |
# Checking whether the given number is even or odd number = 947 print(number, ‘is’, ‘even’ if number % 2 == 0 else ‘odd’) OUTPUT: 947 is odd |
# Transposing a matrix with the help of list comprehension determinant = [[3, 9], [4,16], [5,25], [6,36], [7,49], [8,64]] transpose_matrix = [[row[i] for row in determinant] for i in range(2)] print(transpose_matrix) OUTPUT: [[3, 4, 5, 6, 7, 8], [9, 16, 25, 36, 49, 64]] |
Set and Dictionary comprehensions
In Python, you can also create a dictionary and set comprehensions. List comprehension and set comprehension in Python are very similar. The difference is that set comprehensions guarantee that the output does not contain any duplicates. Curly braces should be used in place of square brackets to produce a set comprehension.
# Set comprehension thought = ‘Working during the internship period gives a lot of exposure and lets us know the real world problems and how to tackle them.’ unique_consonants = {i for i in thought if i not in ‘aeiou’} print(unique_consonants) OUTPUT: {‘x’, ‘t’, ‘l’, ‘g’, ‘v’, ‘n’, ‘W’, ‘s’, ‘r’, ‘h’, ‘ ‘, ‘c’, ‘.’, ‘k’, ‘p’, ‘d’, ‘w’, ‘f’, ‘m’, ‘b’} |
# cube from 1 to 10 with the help of set comprehension cubes = {j:j**3 for j in range(11)} print(cubes) OUTPUT: {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729, 10: 1000} |
How to apply List comprehension in DataFrames
In this section, we will see how to apply the list comprehension technique in a Pandas DataFrame. In the below block of code, if the student’s mark is greater than 90, then it will be a “high mark,” or else it will be a “less mark.”
import pandas as pd  df = pd.DataFrame({‘Name’: [‘Ram’, ‘Lakshman’, ‘Maruti’, ‘Sita’],         ‘Marks’: [100, 88.5, 95.66, 89]})  df[‘Class’] = [“high mark” if x >= 90 else “less mark” for x in df[‘Marks’]] print(df) |
Performance comparison of list comprehension, map function, and for loop
import random import timeit increment_rate = 0.9 # using a list comprehension to randomly generate values upto 100 for the range of 100000 students marks = [random.randrange(100) for _ in range(100000)] # a function to add the increment percentage of student’s marks def get_marks(mark):   return (mark * (1+increment_rate))  # function using comprehension to pass the increment marks def mark_comphrension():   return[get_marks(mark) for mark in marks]  # function using map function to pass the increment marks def get_marks_map():   return list(map(get_marks,marks))  # using for loop to pass the increments in the marks by appending to an empty list scores def get_marks_loop():   scores = []   for mark in marks:     scores.append(get_marks(mark))   return scores print(“Time taken by list comprehension in seconds is”,timeit.timeit(mark_comphrension, number=200)) print(“Time taken by map function in seconds is”,timeit.timeit(get_marks_map, number=200)) print(“Time taken by loop in seconds is”,timeit.timeit(get_marks_loop, number=200)) OUTPUT: Time taken by list comprehension in seconds is 3.071753904000005 Time taken by map function in seconds is 2.4523929979999934 Time taken by loop in seconds is 3.7325495309999894 |
The timeit function is used to calculate how long it took the three functions to execute 200 times. In the preceding scenario, we saw that the map function was the quickest, followed by list comprehension, and the loop was the slowest. Depending on your program’s requirements, list comprehension may or may not be important. There isn’t a strict guideline for which technique should be used; it all depends on the problem description.
If you want to find a cube of 1000 numbers, for example, list comprehension can be used without issue. However, if you want to find the cube of the first billion numbers or the Fibonacci sequence of billions, list comprehension isn’t a wise choice because it creates a list of 1 billion integers.
As a result, your computer may become unresponsive or crash because it has used up all of its memory. In this case, the generator saves time and resources. because a generator returns an iterable rather than building a single, substantial data structure in memory. While only storing one item at a time, your code can repeatedly request the next value from the iterable until it reaches the end of the sequence.
sum(i * i for i in range(99999999999)) |
The absence of an extra set of square brackets is the key distinction between list comprehension and generator.
Conclusion
In this blog, we went over a variety of list comprehension usage scenarios and even looked at a time comparison between list comprehension, map, and for loops. In this post, we discussed conditional logic, nested loops, dataframes, set comprehensions, and dictionaries. The best way to learn will be through practice only so try to implement all these ideas in your projects or tasks. Your helpful criticism and recommendations are greatly appreciated as I work to improve.