Newbiequestion about lists and arrays....

Erik Max Francis max at alcyone.com
Sat Sep 6 23:26:29 CEST 2003


Michael wrote:

> I would like to use an multidimensional matrix (3D or more) with
> numbers (int:s and float:s). Could i use lists or arrays? How can i
> retrieve a single element out of a list thats already in an other list
> thats already in an other list (and so on...)

It's because Python doesn't have copy semantics.  You're building a list
of lists of lists, some of whose elements are references to the same
list.

To ensure that these lists are all distinct objects, and thus giving you
the expected behavior, don't use references to previous objects; create
new ones instead:

>>> c = []
>>> for x in range(3):
...  xs = []
...  for y in range(3):
...   ys = []   
...   for z in range(3):
...    ys.append([1, 2, 3])
...   xs.append(ys)
...  c.append(xs)
... 
>>> c
[[[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]],
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]], [[[1, 2, 3], [1, 2, 3], [1, 2, 3]],
[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]],
[[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]],
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]]]
>>> c[1][1][1] = 888
>>> c
[[[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]],
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]], [[[1, 2, 3], [1, 2, 3], [1, 2, 3]],
[[1, 2, 3], 888, [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]], [[[1,
2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2,
3], [1, 2, 3], [1, 2, 3]]]]

There are other ways to do the job, of course, involing say list
comprehensions.

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ You're wasting time / Asking what if / You linger on too long
\__/  Chante Moore




More information about the Python-list mailing list