×

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

Python Examples

In this tutorial, we will see some examples related to python. This will include some basic example questions and their code in Python. Write a program to print “Hello Python”. print(‘Hello Python’) Output Hello...

5 minutes read.

Python reversed() Function

Python reversed() Function The reversed() in Python returns a reverse iterator. Syntax reversed(seq) Parameter seq: This parameter represents any iterable object. Return This function returns a reversed iterator object. Example 1 # Python Program describing # the reversed() function ...

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 vs Java

There are a lot of programming languages out there, and every day, a new programming language is developing in some parts of the world. Each programming language is a mixture...

5 minutes read.

Python Logistic Regression with Sklearn & Scikit

In this article, we'll walk through a tutorial for utilising the Python Sklearn (formerly known as Scikit Learn) package to implement logistic regression. To assist you in remembering the concept,...

18 minutes read.

Python Function

Python Function A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a...

7 minutes read.

Difference between Module and Package in Python

The main difference between the module and the package in Python is that the module can be a simple file in Python that contains the different functions and collection of...

4 minutes read.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

Python Dictionary keys() method

Python Dictionary keys() method The dictionary.keys() method in Python returns a view object that displays a list of all the keys in the dictionary Syntax dictionary.keys() Parameter NA Return This method returns a view object that displays...

2 minutes read.

Python md5() function

Python md5() function The md5() function in PHP calculates the md5 hash of a string. Syntax md5 ( string $str [, bool $raw_output] ) Parameter str(required)- This parameter specifies the string. raw_output(optional)- This parameter specifies a hex or binary output format: TRUE - Raw 16 character binary...

1 minute read.

Excel to CSV in Python

Define MS Excel Microsoft Excel is an application provided by the Microsoft corporation which allows us to build graphs to build tables, and it is also used for the macro programming...

4 minutes read.

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Python bytearray()

Python bytearray() Class The bytearray() class is used to return a bytearray object which is an array of the specified bytes. It gives a mutable sequence of integers in the range 0...

1 minute read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

Pillow Python introduction and setup

Introduction Advanced image processing implies handling the picture carefully with the assistance of a PC. Utilizing picture handling we can perform activities like upgrading the picture, obscuring the picture, separating text...

4 minutes read.

Python Escape Characters

In this tutorial, we will learn how to use the Escape Characters in Python. Escape Character: Escape Characters are used for some special meaning in our statements. It is denoted or represented...

3 minutes read.

Why learn Python?

All things considered, learning python would be extraordinary, it'll acquaint you with the universe of dynamic programming dialects, if you're somebody who has had a semester of involvement with C. Python...

4 minutes read.

Best Database for Python

Database The collection of structured data or information in an organized format in a computer system is known as Database. The data is inserted, deleted, updated, controlled, or manipulated in a...

6 minutes read.

Compound Interest GUI Calculator using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.