Share your knowledge at the LQ Wiki.
 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, 09: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, 05: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, 03: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

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is Off HTML code is Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post som_kurian Programming 6 12-05-2007 11:43 PM sdlinwwin Linux - Software 1 03-27-2007 01:28 PM datbenik Programming 1 01-05-2006 05:12 AM TroelsSmit Linux - Newbie 2 02-22-2005 04:55 AM banerji Programming 2 07-12-2004 07:27 PM

LinuxQuestions.org

All times are GMT -5. The time now is 02:14 PM.

 Contact Us - Advertising Info - Rules - LQ Merchandise - Donations - Contributing Member - LQ Sitemap -