[Tutor] Matrix bug

Alan Gauld alan.gauld at btinternet.com
Sun Apr 5 23:46:51 CEST 2015


On 05/04/15 15:12, Narci Edson Venturini wrote:
> The next code has an unexpected result:
>
>>>> a=3*[3*[0]]

Note that this makes three references to
the list of 3 references to 0.
In other words you reference the same list 3 times.
So when you change the first copy you change the
other 2 also.

Put another way:

 >>> mylist = [0,0,0]
 >>> a = 3 * [mylist]

'a' now contains 3 references to mylist, making
4 references altogether to the same list object.
If I change the list via any of them it will
change in all the places it is referenced:

 >>> mylist[0] = 1   # replace a zero with a one
 >>> mylist
[1, 0, 0]
 >>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

> When the followind code is ran, them the correct result is obtained:
>
>>>> a=[[0 for i in range(3)] for j in range(3)]

This created 3 new lists. In fact you could simplify it to:

a = [[0,0,0] for i in range(3)]

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list