×

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.


Related Topics

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Python String Lowercase

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

Python for Data Analysis

Data analysis uses various techniques to read, illustrate, manipulate and evaluate a particular data. You can have access to the data and keep the data updated regularly. You can append...

4 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Convert XML to JSON in Python

XML conversion is very useful if we work on an API that returns data in JSON format and the source of data is in XML format. JSON A JSON file reserves the...

4 minutes read.

Classes & Objects in Python

Classes and Objects are used in most modern programming languages, mainly in Object-oriented Programming languages. What is meant by Object Oriented Programming language? Usage of objects and their components in order to...

7 minutes read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

Python Operators

Operators in Python programming An operator is a symbol that operates on one or more operands. An operand is a value or a variable on which we perform the operation....

5 minutes read.

How to Download all Modules in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Virtual Environment

In this tutorial, we will understand Virtual Environment in Python. We will understand the need for a virtual environment and also see how to make use of it in python....

3 minutes read.

Python String title() method

Python String title() method The string.title() method in Python returns a string where the first character in every word is upper case. If the word contains a number or a symbol,...

1 minute read.

Python sklearn train_test_split

Sklearn: One of the most beneficial open-source libraries for learning algorithms in Python is, without a doubt, Sklearn or Scikit-Learn. The most effective tools for statistical modeling and machine learning are all included in...

6 minutes read.

Copying a file from one folder to Another with Python

In this article, we shall discuss copying a file from one folder to another using python functions. A file is a collection of data or information stored on a computer....

3 minutes read.

How to Concat two Dataframes in Python

Using Pandas dataframe, we can concat two dataframes or series in Python. So let's take a brief introduction to what is Pandas in Python. Pandas is a library typically used for...

7 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Python input() function

Python input() function The input() function in Python reads a line from input and converts it to a string (stripping a trailing newline). Syntax input([prompt]) Parameter prompt: This function represents a string, depicting a default...

1 minute read.

Math Module in Python

In this article, you are going to learn everything in detail about the “ math “ module in Python. We can normally work with general operations using python without importing or...

16 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

3 minutes read.