using "*" to make a list of lists with repeated (and independent) elements
TP
TP at frenoespam.fr.invalid
Wed Sep 26 17:20:10 EDT 2012
More information about the Python-list mailing list
Wed Sep 26 17:20:10 EDT 2012
- Previous message (by thread): FirePlus
- Next message (by thread): using "*" to make a list of lists with repeated (and independent) elements
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Hi everybody, I have tried, naively, to do the following, so as to make lists quickly: >>> a=[0]*2 >>> a [0, 0] >>> a[0]=3 >>> a [3, 0] All is working fine, so I extended the technique to do: >>> a=[[0]*3]*2 >>> a [[0, 0, 0], [0, 0, 0]] >>> a[0][0]=2 >>> a [[2, 0, 0], [2, 0, 0]] The behavior is no more expected! The reason is probably that in the first case, 0 is an integer, not a list, so Python copies two elements that are independent. In the second case, the elements are [0,0,0], which is a list; when Python copies a list, he copies in fact the *pointer* to the list, such that we obtain this apparently strange behavior. Is it the correct explanation? In these conditions, how to make this list [[0,0,0],[0,0,0]] with "*" without this behavior? Thanks, TP
- Previous message (by thread): FirePlus
- Next message (by thread): using "*" to make a list of lists with repeated (and independent) elements
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list