Updated April 17, 2023
Introduction to List Comprehensions Python
The following article provides an outline for 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, 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 representing members of the iterable is 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:
Let’s consider doing the same, using List Comprehensions instead of a loop.
Code:
numbers = [2, 5, 3, 7]
square = [n**2 for n in numbers]
print(square)
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 functions 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 readable and more accessible to understand by someone who is not a code programmer.
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 look at how we can use nested loops 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
Given 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])
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:
Advantage
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, the time it takes to complete the task and the amount of memory needed. When a list comprehension is made, we are already reducing 3 lines of code into one. When done, the code is far faster than when facing a list comprehension. Python allocates the memory for the list first and then adds elements inside it. Also, it is undoubtedly a more elegant and sophisticated way of creating lists based on pre-existing lists.
Conclusion
Now that we have experience with list comprehensions, it is easy to understand how these allow us to transform one list into a new one. These have a simple syntax limiting the amount of work needed to create a list. Considering the syntax and structure of list comprehensions are 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
We hope that this EDUCBA information on “List Comprehensions Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.