Skip to main content

Command Palette

Search for a command to run...

Nested list comprehension

Published
2 min readView as Markdown
Nested list comprehension
X

"I am currently a Software Engineering student at ALX. I'm passionate about technology and enjoy conducting research to find answers on my own. I have a natural inclination to ask 'WHY' more often than 'HOW'.

"While working on projects at ALX, I have acquired a wealth of interesting and diverse knowledge about software engineering and computer science in general. Therefore, I needed a place to store and save all this information, allowing me to refer back to it whenever I forget."

matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

The following list comprehension will transpose rows and columns:

[[row[i] for row in matrix] for i in range(4)]

#output
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

Now how does this work?
Here, for i in range(4) is the outer loop and gets executed first
for row in matrix is the inner loop.

I was trying to solve it with for row in matrix as the first loop and I was getting wrong answers.

Let's break down the code step by step to understand how each element in the new list is generated:

  1. The code [[row[i] for row in matrix] for i in range(4)] uses a nested list comprehension to generate the new list.

  2. Let's consider the outer loop for i in range(4):

    • For i = 0, the inner loop [row[i] for row in matrix] will iterate over each row in the matrix and extract the element at index 0 for each row.

      • In the first iteration of the inner loop, row will be [1, 2, 3, 4]. So, row[i] will be row[0] which is 1.

      • In the second iteration, row will be [5, 6, 7, 8], and row[i] will be row[0] which is 5.

      • In the third iteration, row will be [9, 10, 11, 12], and row[i] will be row[0] which is 9.

Therefore, the first element of the new list will be 1, the second element will be 5, and the third element will be 9.

  1. Combining the results of the outer loop, we get [1, 5, 9]. This represents the first column of the original matrix.

i gets incremented to 1, and the same process repeats again.

To summarize, in the given code, the first element [1, 5, 9] in the new list is generated by extracting the first element from each row of the original matrix. This is achieved using the inner loop [row[i] for row in matrix], where row[i] accesses the element at index i for each row.

More from this blog

PERSONAL BLOG

110 posts

Use the search button to search for a specific topic or keyword *all posts are updated on the go*