0

Why does this code doesn't transpose the list of list

import sys
t = input()
for k in range(t):
  n,m = [int(i) for i in raw_input().strip().split()]
  A = [[None]*m]*n
  B = [[None]*n]*m
  for l in range(n):
    A[l] = raw_input().strip().split()
  for j in range(m):
    for i in range(n):
    B[j][i] = A[i][j]

  print B

I know there are better methods to transpose a matrix but why does this doesn't work?

  • Possible duplicate of http://stackoverflow.com/questions/6473679/python-list-of-lists-transpose-without-zipm-thing? – BrockLee Feb 06 '16 at 04:30

1 Answers1

0

Replace

A = [[None]*m]*n
B = [[None]*n]*m

with

A = [[None for x in range(m)] for x in range(n)]
B = [[None for x in range(n)] for x in range(m)]

Why?

>>> l = [2]*5
>>> l
[2,2,2,2,2]
>>> [id(value) for value in l]
[26089400, 26089400, 26089400, 26089400, 26089400]

Can you see what happened there? There's just one copy in memory holding a value '2'. All list elements are pointing to that same memory location holding the value '2'.

So, when you do:

A = [[None]*m]*n

you are creating a 2d array with elements pointing to the same memory location. Changing one of them, changes the value stored at that common memory location, hence changes value stored by all the elements!

That is why the program didn't work.

Read more about how all this works in Python, in detail, here: http://foobarnbaz.com/2012/07/08/understanding-python-variables/

Prajwal K R
  • 682
  • 5
  • 14