Saturday, 15 September 2012

Appending a list to another list through iteration in python -



Appending a list to another list through iteration in python -

so, i've been trying create matrix consisting of multiplication tables n python.

my function goes this:

def multiplicationtable(n): tableprint = [] temptable = [] s in range(n): s += 1 temptable.clear() r in range(n): r += 1 temptable.append(r*s) tableprint.append(temptable) # print(tableprint) homecoming tableprint

however, returned list consists of n versions of nth temptable. if remove comment, can see through each iteration, every single instance within tableprint gets edited. had friend explain lists not data, memory address set of data, why doesn't work?

the issue appending temptable object repeatedly tableprint object. thus, when modify temptable, modify instances of in tableprint. called mutability, in python lists mutable. not info in python mutable, example, approach wold work if temptable string.

to around issue mutable info append copy:

tableprint.append(temptable[::])

here's little example:

>>> = [1,2,3] >>> b = >>> == b true >>> b true #they same object, changing alter b >>> b = a[::] >>> == b true >>> b false #they no longer same object!

the issue having discussed in length here (in different form)

python list python-3.x

No comments:

Post a Comment