matrix - Transposing a list of lists in python -


why code doesn't transpose list of list

import sys t = input() k in range(t):   n,m = [int(i) in raw_input().strip().split()]   = [[none]*m]*n   b = [[none]*n]*m   l in range(n):     a[l] = raw_input().strip().split()   j in range(m):     in range(n):     b[j][i] = a[i][j]    print b 

i know there better methods transpose matrix why doesn't work?

replace

a = [[none]*m]*n b = [[none]*n]*m 

with

a = [[none x in range(m)] x in range(n)] b = [[none x in range(n)] x in range(m)] 

why?

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

can see happened there? there's 1 copy in memory holding value '2'. list elements pointing same memory location holding value '2'.

so, when do:

a = [[none]*m]*n 

you creating 2d array elements pointing same memory location. changing 1 of them, changes value stored @ common memory location, hence changes value stored elements!

that why program didn't work.

read more how works in python, in detail, here: http://foobarnbaz.com/2012/07/08/understanding-python-variables/


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -