Declare list of large size
David Eppstein
eppstein at ics.uci.edu
Mon Mar 18 19:43:03 EST 2002
In article <mailman.1016495070.23614.python-list at python.org>,
"Delaney, Timothy" <tdelaney at avaya.com> wrote:
> > 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!
I got bitten by that, once. It took very little time to learn not to do
that.
So, is it considered more Pythonic to create a multidimensional array by
list = [[0]*100 for i in range(100)]
and then access it by
...list[i][j]...
or is it more typical to just use dictionaries?
list = {}
...list[i,j]...
?
I can see advantages either way -- the dictionary method is simpler,
more space-efficient if you don't intend to fill the whole thing, and
makes it easy to pass around and use tuples representing indexes into
the array. But the list-of-lists more explicitly states what you're
doing, may be slightly faster (I haven't checked), gives you bounds
checking,and more generally doesn't let you index by anything but a
tuple of integers.
--
David Eppstein UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list