views:

1375

answers:

6
+4  Q: 

arrays in python

Hi I just started work on my first python script What's the best way to create 2 D arrays in python ? What I want is want is to store values like this : X , Y , Z so that I access date like X[2],Y[2],Z[2] or X[n]Y[n],Z[n] where n is varialble I don't know in the beginning how big n would be so I would to append values at the end

+5  A: 

In Python one would usually use lists for this purpose. Lists can be nested arbitrarily, thus allowing the creation of a 2D array. Not every sublist needs to be the same size, so that solves your other problem. Have a look at the examples I linked to.

Stephan202
+4  A: 
>>> a = []

>>> for i in xrange(3):
...     a.append([])
...     for j in xrange(3):
...             a[i].append(i+j)
...
>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>>
Perica Zivkovic
I would write this in a functional way - That's much more concise:`a = [[i + j for j in range(3)] for i in range(3)]`
Dario
+3  A: 

If you want to do some serious work with arrays then you should use the numpy library. This will allow you for example to do vector addition and matrix multiplication, and for large arrays it is much faster than Python lists.

However, numpy requires that the size is predefined. Of course you can also store numpy arrays in a list, like:

import numpy as np
vec_list = [np.zeros((3,)) for _ in range(10)]
vec_list.append(np.array([1,2,3]))
vec_sum = vec_list[0] + vec_list[1]  # possible because we use numpy
print vec_list[10][2]  # prints 3

But since your numpy arrays are pretty small I guess there is some overhead compared to using a tuple. It all depends on your priorities.

See also this other question, which is pretty similar (apart from the variable size).

nikow
I pondered talking about this, and yes, this is a useful addition. Isn't it the case, though, that numpy requires fixed-length arrays?
Stephan202
True, thanks, I modified the answer to address this more clearly.
nikow
+3  A: 

Depending what you're doing, you may not really have a 2-D array.

80% of the time you have simple list of "row-like objects", which might be proper sequences.

myArray = [ ('pi',3.14159,'r',2), ('e',2.71828,'theta',.5) ]

myArray[0][1] == 3.14159
myArray[1][1] == 2.71828

More often, they're instances of a class or a dictionary or a set or something more interesting that you didn't have in your previous languages.

myArray = [ {'pi':3.1415925,'r':2}, {'e':2.71828,'theta':.5} ]

20% of the time you have a dictionary, keyed by a pair

myArray = { (2009,'aug'):(some,tuple,of,values), (2009,'sep'):(some,other,tuple) }

Rarely, will you actually need a matrix.

You have a large, large number of collection classes in Python. Odds are good that you have something more interesting than a matrix.

S.Lott
+1  A: 

I would suggest that you use a dictionary like so:

arr = {}

arr[1] = (1, 2, 4)
arr[18] = (3, 4, 5)

print(arr[1])
>>> (1, 2, 4)

If you're not sure an entry is defined in the dictionary, you'll need a validation mechanism when calling "arr[x]", e.g. try-except.

Roee Adler
If you want a multidimensional 'array' you can use tuples as keys in the dicts, like this: arr[(1, 20)] = 12
Rory
+1  A: 

If you are concerned about memory footprint, the Python standard library contains the array module; these arrays contain elements of the same type.

EOL