Declare list of large size

Delaney, Timothy tdelaney at avaya.com
Mon Mar 18 18:43:00 EST 2002


> From: marduk [mailto:marduk at python.net]
> 
> On Mon, 2002-03-18 at 16:44, Aaron Ginn wrote:
> > 
> > Perhaps I've just glossed over this in the documentation, 
> but what is
> > the simplest way to declare a list of large size?  Is there 
> something
> > analogous to the following in C:
> > 
> > int list[100];
> > 
> 
> list = [0]*100

But note that this is only safe for immutable elements. You will obtain a
reference to the *same* object as each element.

This normally bites people when they try to make multi-dimensional arrays
...

list = [[0] * 2] * 2
print list
list[0][0] = 1
print list

[[0, 0], [0, 0]]
[[1, 0], [1, 0]]

As you can see, the first element of each sub-list has been changed - this
is because each sub-list is in fact the same list!

Tim Delaney




More information about the Python-list mailing list