Support LQ: Use code LQ3 and save \$3 on Domain Registration
 Home Forums HCL Reviews Tutorials Articles Register Search Today's Posts Mark Forums Read
 LinuxQuestions.org python; multidimensional "arrays"
 Programming This forum is for all programming questions. The question does not have to be directly related to Linux and any language is fair game.

Notices

 12-06-2007, 10:30 AM #1 horacioemilio Member   Registered: Dec 2007 Posts: 61 Rep: python; multidimensional "arrays" in python, when I want to use arrays, I follow this way; DATA = [0] * nint and when I want to use I do; .... DATA[i] = .... do you know how to do similar but in two dimensions ? thanks
 12-06-2007, 06:49 PM #2 ghostdog74 Senior Member   Registered: Aug 2006 Posts: 2,697 Blog Entries: 5 Rep: maybe this Code: ```>>> e = [[0] * 3]*3 >>> e [[0, 0, 0], [0, 0, 0], [0, 0, 0]]```
12-07-2007, 04:03 PM   #3
LQ Newbie

Registered: Jul 2007
Location: Bristol UK
Distribution: RedHat, Cygwin
Posts: 14

Rep:
Quote:
 Originally Posted by ghostdog74 maybe this Code: ```>>> e = [[0] * 3]*3 >>> e [[0, 0, 0], [0, 0, 0], [0, 0, 0]]```
You would duplicate references to the same list if you did the above.

Here is an example:
Code:
```>>> e = [[0] * 3]*3
>>> e
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> e[0][1]
0
>>> e[0][1] =3.141
>>> e
[[0, 3.141, 0], [0, 3.141, 0], [0, 3.141, 0]]```

Instead create a list of lists without duplicate references. Here is one way:
Code:
```>>> e = [[[] for inner in range(3)] for outer in range(4)]
>>> e
[[[], [], []], [[], [], []], [[], [], []], [[], [], []]]
>>> len(e)
4
>>> len(e[0])
3
>>> for outer in range(4):
... 	for inner in range(3):
... 		e[outer][inner] = (outer,inner)
...
>>> e
[[(0, 0), (0, 1), (0, 2)], [(1, 0), (1, 1), (1, 2)], [(2, 0), (2, 1), (2, 2)], [(3, 0), (3, 1), (3, 2)]]
>>>```

 Tags array, python