KSouthwick
KSouthwick

Reputation: 9

python nested list comprehensions

I am learning python and going through their tutorials. I understand list comprehensions and nested lists comprehensions. With the following code, though, I am trying to understand the order of events.

>>> matrix = [
...[1, 2, 3, 4],
...[5, 6, 7, 8],
...[9, 10, 11, 12],
... ]
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4,8,12]]

According to the nested list comprehension, is the first "i" and the second "i" the same variable and do they both increase at the same time? I guess I don't understand how the resulting big list goes from the first sublist [1, 5, 9] to the second sublist [2, 6, 10]

Upvotes: 1

Views: 247

Answers (2)

Julien Faujanet
Julien Faujanet

Reputation: 57

I made a function in order to do it automatically (sorry for the example, i took it from someone) :

Let's say, you have this example :

# 2-D List 
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] 
  
flatten_matrix = [] 
  
for sublist in matrix: 
    for val in sublist: 
        flatten_matrix.append(val) 

This is my function : (first, turn the example into a string that you will send to the function)

x = "for sublist in matrix:for val in sublist:flatten_matrix.append(val)"

then the function :

def ComprenhensionizeList(nested_for_loop_str):

    splitted_fors = nested_for_loop_str.split(':')
    lowest_val = splitted_fors[1].split(' ')[1]
    comprehensionizer = '[ '+ lowest_val+' '+splitted_fors[0]+' '+splitted_fors[1]+' ]'
    print(comprehensionizer)

and the output :

[ val for sublist in matrix for val in sublist ]

Upvotes: 0

Delgan
Delgan

Reputation: 19697

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

is equivalent to

my_list = []
for i in range(4):
    my_list_2 = []
    for row in matrix:
        my_list_2.append(row[i])
    my_list.append(my_list_2)


is the first "i" and the second "i" the same variable and do they both increase at the same time?

Of course, it is. If it was not the same i, the code would throw an error because one of the two would not be defined.

You may be interested in this question: Understanding nested list comprehension

Upvotes: 1

Related Questions