Matrix List Comprehension in Python
Introduction
One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which are quite similar to nested for loops, are nothing more than a list comprehension inside of another list comprehension.
What is List Comprehension?
A list can be defined and created in Python with the help of list comprehension. Like mathematical assertions, lists can be created in a single line. List comprehension's syntax is simpler to understand.
These components often make up a list comprehension:
- Expression for output,
- Input pattern,
- A variable that represents one of the input sequence's participants, and
- A possible predicate component.
For Example:
# List comprehension in Python is demonstrated using a Python program.
# The list below shows the squares of all odd numbers from 1 to 10.
odd_sqr = [a ** 2 for a in range(1, 11) if a % 2 == 1]
print (odd_sqr)
# For clarity, the above generation is the same as,
odd_sqr = []
for a in range(1, 11):
if a % 2 == 1:
odd_sqr.append(a**2)
print (odd_sqr)
# The following list covers powers of 2 ranging from 1 to 8.
powerOfTwo = [2 ** a for a in range(1, 9)]
print (powerOfTwo)
# The following list stores prime and non-prime numbers ranging from 1 to 50.
no_primes = [l for k in range(2, 8) for l in range(k*2, 50, k)]
prime = [a for a in range(2, 50) if a not in no_primes]
print (prime)
# list of characters to be lower
print ([a.lower() for a in ["A","B","C"]] )
# a list that extracts numbers
str = "my phone number is : 11122 !!"
print ("\nExtracted digits")
num = [a for a in str if a.isdigit()]
print (num)
# A list of tables for multiplication
a = 5
tbl = [[a, b, a * b] for b in range(1, 11)]
print("\nMultiplication Table")
for k in tbl:
print (k)
Output:
[Running] python -u "d:\Programming\Python\test.py"
[1, 9, 25, 49, 81]
[1, 9, 25, 49, 81]
[2, 4, 8, 16, 32, 64, 128, 256]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
['a', 'b', 'c']
Extracted digits
['1', '1', '1', '2', '2']
Multiplication Table
[5, 1, 5]
[5, 2, 10]
[5, 3, 15]
[5, 4, 20]
[5, 5, 25]
[5, 6, 30]
[5, 7, 35]
[5, 8, 40]
[5, 9, 45]
[5, 10, 50]
[Done] exited with code=0 in 0.304 seconds
List Comprehension Examples
To better understand what nested or matrix list comprehensions are capable of, let's look at some examples:
Example 1:
I want to make a matrix that appears as follows:
matrix = [[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5]]
For the specified task, the code below used nested for loops:
Code:
matx = []
for k in range(6):
# Add a bare sublist at the end of the list.
matx.append([])
for l in range(6):
matx[k].append(l)
print(matx)
Output:
[Running] python -u "d:\Programming\Python\test.py"
[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]
[Done] exited with code=0 in 0.312 seconds
With nested list comprehension, the same result can be produced in a single line:
Code:
# Nested or matrix list comprehension
matx = [[l for l in range(6)] for k in range(6)]
print(matx)
Output:
[Running] python -u "d:\Programming\Python\test.py"
[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]
[Done] exited with code=0 in 0.27 seconds
Explanation:
The following is a list of the program's syntax:
[expression for k in range(6)] denotes that the expression should be executed and the results appended to the list up until the variable k iterates from 0 to 5.
As an instance: [k for k in range (6)] –> Since the variable k itself is the outcome of the expression in this instance, we added its output to the list as k iterates from 0 to 5.
Consequently, the result would be [0, 1, 2, 3, 4, 5]
However, in this instance, the expression is a list comprehension. Therefore, we must first solve the expression before adding the result to the list.
However, in this instance, the expression is a list comprehension. Therefore, we must first evaluate the expression before adding the result to the list.
Expression = [l for l in range(6)] -> This expression's result is the same as that of the previous example.
Expression is therefore [0, 1, 2, 3, 4, 5].
Now, all that is left to do is to incrementally add this output until variable k iterates from 0 to 5, which would be
six iterations total. In light of this, the ultimate result would be simply a list of the results of the
above expressions repeated six times.
Output: [[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]
Example 2:
Let's say I wish to flatten a certain 2-D list:
matrix = = [[6, 4, 2], [7, 2], [8, 7, 5, 3]]
Flat_matrix = [6, 4, 2, 7, 2, 8, 7, 5, 3]is the desired result.
Nested for loops can be used to accomplish the following:
Code:
# Two-Dimensional List
matx= [[6, 4, 2], [7, 2], [8, 7, 5, 3]]
flat_matrix = []
for sub_list in matx:
for val in sub_list:
flat_matrix.append(val)
print(flat_matrix)
Output:
[Running] python -u "d:\Programming\Python\test.py"
[6, 4, 2, 7, 2, 8, 7, 5, 3]
[Done] exited with code=0 in 0.348 seconds
Again, nested list comprehension can be used for this, as demonstrated below:
Code:
# Two-Dimensional List
matx = [[6, 4, 2], [7, 2], [8, 7, 5, 3]]
# Nested or matrix List Comprehension to flat a given list 2-Dimensional matrix
flat_matrix = [val for sub_list in matx for val in sub_list]
print(flat_matrix)
Output:
[Running] python -u "d:\Programming\Python\test.py"
[6, 4, 2, 7, 2, 8, 7, 5, 3]
[Done] exited with code=0 in 0.314 seconds
Explanation:
In this situation, we must loop through the given two-dimensional list and append each entry to another list. We can separate the list comprehension into sections for easier comprehension.
Three sections:
flat_matrix = [val
for sub_list in matx
for val in sub_list]
The first line indicates what we wish to add to the list. The second line represents the outside loop, while the third line represents the inner loop.
'forsub_list in matx' returns the sub_lists contained within the matrix one by one, as follows:
[[6, 4, 2], [7, 2], [8, 7, 5, 3]]
'forval in sub_list' returns, all of the values included within the sub_list.
As a result, if sub_list = [6, 4, 2], 'for val in sublist' -> outputs 6, 4, 2 one by one.
We get the outcome as val for each such val and add it to the list.
Example 3:
Assume I would like to flat a given 2-D list and include only strings with lengths less than 6:
planet = [[‘Mercury’, ‘Venus’, ‘Earth’], [‘Mars’, ‘Jupiter’, ‘Saturn’], [‘Uranus’, ‘Neptune’, ‘Pluto’]]
Output: Flat planets = ['Venus,' 'Earth,' 'Mars,' 'Pluto']
This can be accomplished by employing an if condition within a nested for loop, as seen below:
Code:
# Two Dimensional List of planets
planet = [['Mars', 'Venus', 'Uranus'], ['Mercury', 'pluto', 'Saturn'], [ 'Earth', 'Neptune', 'Jupiter']]
flat_planets = []
for sub_list in planet:
for planet in sub_list:
if len(planet) < 6:
flat_planets.append(planet)
print (flat_planets)
Output:
[Running] python -u "d:\Programming\Python\test.py"
['Mars', 'Venus', 'pluto', 'Earth']
[Done] exited with code=0 in 0.301 seconds
This can also be accomplished with nested list comprehensions, as demonstrated below:
Code:
# Two Dimensional List of planets
planet = [['Mars', 'Venus', 'Uranus' ], ['Mercury', 'pluto' , 'Saturn'], [ 'Earth', 'Neptune', 'Jupiter']]
# Understanding of nested lists with an if the condition
flat_planets = [planet for sub_list in planet for planet in sub_list if len(planet) < 6]
print (flat_planets)
Output:
[Running] python -u "d:\Programming\Python\test.py"
['Mars', 'Venus', 'pluto', 'Earth']
[Done] exited with code=0 in 0.353 seconds
Explanation:
This example is very similar to the previous one, but in this case, we simply require an extra if condition to determine whether the length of a specific planet is less than 6 or not.
This can be broken down into four parts:
flat_planets = [planet
for sub_list in planet
for planet in sub_list
if len(planet) < 6]
Conclusion
List comprehension is a unique feature of Python which allows coders to create elegant and simple programs. Not only does using list comprehension save lines of code, but it is generally easier to comprehend than alternative ways.
While list comprehension is commonly thought to be more "Pythonic" than other approaches, such as for loops, this is not always the case. Python code is intended to be flexible and efficient. Every Python tool has advantages and disadvantages.
To make the most of Python list comprehension, we can filter the results with a condition. Filters increase the versatility of list comprehension expressions.