Introduction to List Comprehensions Python
Comprehension is a way of building a code block for defining, calling, and performing operations on a series of values/ data elements. A python is a simple object-oriented programming language widely used for the web-based application development process, which grants a variety of list comprehension methods. Some of them are lists, sets, dictionaries, etc. There are three different types of components for the list comprehension functions in python, like the iterables, the Iterator variable for representing the members of the iterables, and the output expression, which is optional and can be ignored.
There are 3 components of List Comprehension, these are:
- Output expression: This one is optional and can be ignored.
- Iterable.
- A variable that represents members of the iterable, it is often called Iterator Variable.
Syntax and Examples
In python, we can create List Comprehensions by using the following syntax:
list_variable = [x for x in iterable]
As you can see in List Comprehensions, a list is assigned to a variable. Let’s take a look at an example; first, we can consider a method to find the square of a number using a loop:
Code:
numbers = [2, 5, 3, 7]
square = []
for n in numbers:
square.append(n**2)
print(square)
Output:
Now, let’s consider doing the same, but using List Comprehensions instead of a loop:
Code:
numbers = [2, 5, 3, 7]
square = [n**2 for n in numbers]
print(square)

4.8 (13,230 ratings)
View Course
Output:
Here, you can see that square brackets “[ ]” are used to denote that the output of expression inside them is a list.
List Comprehensions and Lambda Functions
It would help if you kept in mind that list comprehensions are not the only way of creating lists; Python has many inbuilt functions and lambda function that can be used, such as :
Code:
letters = list(map(lambda x: x, 'human'))
print(letters)
Output:
While this works in many cases, List Comprehensions are better at readability and easier to understand by someone who is not the programmer of the code.
Adding Conditionals in List Comprehensions
You are free to use any conditional needed inside a list comprehension to modify the existing list. Let’s take a look at an example that uses conditionals:
Code:
numbers_list = [ x for x in range(20) if x % 2 == 0]
print(numbers_list)
Output:
Here is another example:
Code:
numbers_list = [x for x in range(100) if x % 2 == 0 if x % 5 == 0]
print(numbers_list)
Output:
Using Nested Loops in List Comprehensions
When needed, we can use Nested Loops in list comprehensions; let us take a look at how we can use nested loops in this way by finding the transpose of a matrix:
Code:
transposedmatrix = []
matrix = [[1, 2, 3, 4], [4, 5, 6, 8]]
for i in range(len(matrix [0])):
transposedmatrix_row = []
for row in matrix:
transposedmatrix_row.append(row[i])
transposedmatrix.append(transposedmatrix_row)
print(transposedmatrix)
Output:
Examples
Below are the examples of List Comprehensions Python:
Example #1 – Removing Vowels from a Given Sentence
Code:
def eg_for(sentence):
vowels = 'aeiou'
filter_list = []
for l in sentence:
if l not in vowels:
filter_list.append(l)
return ''.join(filter_list)
def eg_lc(sentence):
vowels = 'aeiou'
return ''.join([ X for X in sentence if X not in vowels])
Now, let’s define the matrix, run the program and then check-out the results:
sentence = "hello from the other side"
print ("loop result: " + eg_for(sentence))
print ("LC result: " + eg_lc(sentence))
Output:
Example #2 – Mapping Names of Countries with their Capitals
Code:
country = [ 'India', 'Italy', 'Japan' ]
capital = [ 'Delhi' , 'Rome', 'Tokyo' ]
output_dict = {}
# Using loop for constructing dictionary
for (key, value) in zip(country , capital):
output_dict[key] = value
print("Output Dictionary using for loop:", output_dict)
Output:
Advantages
One may think if Loops can be used to do almost everything list comprehensions do, why use them in the first place? Well, the answer is in speed, and the time it takes to get the task done and the amount of memory needed. When a list comprehension is made, we are already reducing 3 lines of code into one, and when it is done, the code is far faster as when facing a list comprehension, python allocates the memory for the list first and then adds elements inside it. Also, it is without a doubt a more elegant and sophisticated way of creating lists that are based on pre-existing lists.
Conclusion
Now that we have had some experience with list comprehensions, it is easy to understand how these allow us to transform one list into a new list. These have a simple syntax that limits the amount of work needed for creating a list. Considering the syntax and structure of list comprehensions is basically like a set-builder notation, these become second nature for programmers quickly and ensure that once the code is handed over to some other person to maintain and expand upon, it will be easy to understand and work with.
Recommended Articles
This is a guide to List Comprehensions Python. Here we discuss list comprehensions and lambda functions along with Code Implementation and Output. You can also go through our other suggested articles to learn more –