No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python List Comprehension Nested For Loops

by Khaleel O.
July 24, 2021
in Python
Reading Time: 3 mins read
A A
python list comprehension nested for loops
python list comprehension nested for loops

Python List Comprehension can be used with Nested For Loops. They can be used, for example, for multi-dimensional matrix operations. Let’s create a 2D matrix first:


matrix = [[col for col in range(4)] for row in range(0,4)]
print(matrix)

#output
#[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]

Let’s explain what’s going on here:

  1. The 2D matrix used here is a python list with sublists which give the illusion of row and columns. It uses a nested for loop in the list comprehension.
  2. [col for col in range(4)] is the inner list comprehension. This creates the columns, which is simply a list of 4 numbers from 0 to 3 inclusive.
  3. [for row in range(0,4)] is the outer for loop which simply repeats the creation of the column list (the inner list comprehension) 4 times to create 4 rows.

When the list comprehension executes we have a new list matrix which is a 2D matrix.

We can now use another nested for-loop in our list comprehension to transpose this 2D matrix. The transpose of a matrix is a flipped version of the original matrix where the rows and columns are switched.

transposedMatrix = [[row[i] for row in matrix] for i in range(4)]
print(transposedMatrix)

#Output
#[[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]

Let’s explain what is going on here:

  1. [row[i] for row in matrix] is the inner list comprehension for loop which takes the ith element of the ith row and uses it to create the column of the transposed matrix.
  2. On the first iteration, it takes the 1st element of the 1st row of the original matrix to create the 1st element of the first row of the new transposed matrix. On the second iteration, it takes 1st element of the 2nd row of the original matrix and adds that element to the first row of the new transposed matrix. It continues this until it fills all 4 members of the first row of the new transposed matrix then it moves on to the next row and so on.
  3. [for i in range(4)] is the outer list comprehension for loop. This simply repeats the process of the inner loop (described above) to create 4 rows. For the first iteration it takes the 1st element of each row of the original matrix to create a new row in the transposed matrix. For the second iteration it takes the 2nd element of each row of the original matrix to create a new row in the transposed matrix, and so on.
  4. transposedMatrix is the transposed matrix that is returned by our nested-for loop list comprehension.

You can actually do the matrix transposition with a traditional for loop. The problem is that it requires much more code and isn’t as concise:

#tmB = transposedMatrixB
tmB = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
for r in range(4):
    for c in range(4):
        tmB[c][r] = matrix[r][c]

print(tmB)

#[[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]

As you can see the result is identical but there is more code required. The point of list comprehensions is to do more with less code.

Hope this tutorial helped. Find the full source code HERE and check out another List Comprehension tutorial HERE. Thanks for reading. 👌👌👌

Tags: list comprehension
Previous Post

Python List Comprehension with Multiple Lists

Next Post

Plot Bar Graph with Python and matplotlib

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy