Declare list of large size
Corrado Gioannini
corrado.gioannini at nekhem.com
Thu Mar 28 09:39:00 EST 2002
On Mon, Mar 18, 2002 at 04:43:03PM -0800, David Eppstein 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]...
another way to build a mutable multidimensional array is simply
>>> list = eval(repr([[0] * 2] * 2))
avoiding the problem of multiple references to the same list object
do you find it too dirty, unpleasant or un-pythonic?
(i'm really asking, it's not an ironic question ;-] )
C.
--
Corrado Gioannini
<gioco at nekhem.com>
-
"Thought is only a flash between two long nights,
but this flash is everything."
(H. Poincaré)
More information about the Python-list
mailing list