How List Comprehension Works in Python
How List Comprehensions Work in Python
In this article, we’ll learn about list comprehensions in Python and how they work.
What are List Comprehensions?
List comprehensions allow us to quickly generate new lists using a sequence or another list we can loop over. In Python, iterables can be looped over. A syntactic technique called list comprehensions makes it possible to build new lists from existing ones. List comprehensions are based on loops (or “for” loops). Any list comprehension can be expressed as a for loop, but it really looks unique when expressed as a single-line equivalent.
List Comprehension – We all know Python is famous for its short syntax, and list comprehension uses an even shorter syntax to help create a new list based on the values of an existing list.
Syntax
newlist = [ expression(element) for element in oldlist if condition ]
Advantages of List Comprehensions
- List comprehensions are more space- and time-efficient than for loops.
-
They require fewer lines of code.
-
They convert iterative statements into formulas.
-
List comprehensions are much faster than for-loops when appending items to a list.
-
List comprehensions are a great alternative to the built-in map and filter functions.
Iterating Through a List Using List Comprehension
Example
# Iterating Through a List Using a Loop and List Comprehension to Create a New List
resultList = [element for element in [5, 10, 15, 20, 25]]
# Printing the Resultant List 1. How do list comprehensions in Python work?
print(resultList)
Output
[5, 10, 15, 20, 25]
Printing odd numbers using list comprehension
Example
The following program uses list comprehension to print all the odd numbers below 20 –
# getting all the odd elements in a range of 20(excluded)
# using list comprehension
OddList = [element for element in range(20) if element % 2 != 0]
# printing all the odd numbers below 20
print(OddList)
Output
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Printing a Matrix Using List Comprehension
Example
The following program uses list comprehension to print a 3×3 matrix.
# creating matrix with 3 rows and 3 columns using list comprehension
inputMatrix = [[n for n in range(3)] for m in range(3)]
# printing the 3x3 matrix
print(inputMatrix)
Output
When executed, the above program will produce the following output –
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
List Comprehension vs. For Loop
Using For Loop
The following program uses a for loop and the append() function to create a list of all the characters of a string –
Example
# iterating through each character in a string
# using list comprehension
resultList = [char for char in 'Tutorialspoint']
# printing the result list containing all the characters
# of a string passed
print(resultList)
Output
['T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't']
Nested List Comprehension
A list comprehension within another list comprehension is called a nested list comprehension
Example
The following program shows the implementation of nested loops —-.
# creating an empty list for storing the result matrix
outMatrix = []
for m in range(3):
# appending an empty sublist to the above-defined output tMatrix
outMatrix.append([])
for n in range(4):
# appending corresponding element to the output Matrix
outMatrix[m].append(n)
# printing the output matrix
print(outMatrix)
Output
When executed, the above program will produce the following output —-.
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
Using nested list comprehensions to implement nested loops
Now, by using nested list comprehensions, you can create the same result with less code.
Example
# creating an empty list for storing the result matrix
# implementing nested loop using Nested list comprehension
# getting a 3*4 matrix
outMatrix = [[n for n in range(4)] for m in range(3)]
# printing the resultant 3*4 matrix
print(outMatrix)
Output
When executed, the above program will produce the following output –
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
Flattening a Multidimensional List Using List Comprehension
Suppose we need to flatten a two-dimensional list. We can easily accomplish this task using a list comprehension and a sublist.
Example
The following program shows the implementation of nested loops.
# input 2-dimensional (2D) list
input2DList = [[4, 6, 1], [2, 5, 3], [0, 1, 2]]
# flattening to a one-dimensional list
flattenList = [value for sublist in input2DList for value in sublist]
# printing the flattened list
print(flattenList)
Output
When executed, the above program will produce the following output –
[4, 6, 1, 2, 5, 3, 0, 1, 2]
Conclusion
This article provided an understanding of list comprehensions and their advantages. To understand how list comprehensions work, we used some examples. We also compared several ways to reduce code size using list comprehensions. To compare code with and without list comprehensions, we used some comparison samples.