1

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]

1
  • Just for fun, note that you can produce these results with zip(*matrix). Commented Jun 29, 2015 at 20:53

2 Answers 2

1
[[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

Sign up to request clarification or add additional context in comments.

Comments

0

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 ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.