[Tutor] Initializing a list as an array
Kalle Svensson
kalle@gnupung.net
Sat, 8 Dec 2001 03:18:15 +0100
[Scott]
> On Friday 07 December 2001 07:24 pm, you wrote:
> >
> > >Suppose I want to initialize a list that I want to use like an
> > >array, setting the initial value of each element to zero.
> > >
> > >>> mylist = [0]*10
> > >>> mylist
> > [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>
> I thought it would be something like that. I played around with several
> variations, but couldn't get it to work. Thanks Kirby.
Just a little warning here, this doesn't extend to multidimensional lists:
>>> mymatrix = [[0]*3]*3
>>> mymatrix
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Seems nice enough, eh? But:
>>> mymatrix[0][0] = 1
>>> mymatrix
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
The reason is that list are mutable objects (i.e. their contents can be
changed during the execution of the program). Integers (such as 0) are not.
mylist = [0] * 3
creates a list containing three references to the object 0.
myarray = [[0] * 3] * 3
creates a list containing three references to a list object containing three
references to the object 0.
Weird? Not helping? Sorry. <wink>
In fact, this (references and mutable/immutable objects) is one of the things
I like very much about Python, but it took me a while to understand it.
Finally, code that does the thing you might expect from the example above:
>>> mymatrix = [[0] * 3 for x in xrange(3)]
>>> mymatrix[0][0] = 1
>>> mymatrix
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
Oh, and I'm sure this is in the FAQ. Hope you don't mind my posting anyway.
Peace,
Kalle
--
Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/ Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]