Entry
Could anybody tell me the command to build a 2D array?
Could anybody tell me the command to build a 2D list?
Nov 17th, 2007 11:11
Harry Parker, unknown unknown, Michael Chermside, Alex Martelli http://numpy.scipy.org/ http://numpy.scipy.org/numpydoc/numdoc.htm
This answer is connected to 2 Python Common Problem questions; one about
making 2D arrays, and another about making 2D lists.
In Python, arrays and lists are 2 very different structures. Lists are
very flexible and can contain arbitrary mixed objects. By making a list
of lists, you create a 2D list of items. Examples are shown below.
Python's built-in array module can make only 1D arrays of numbers or
characters. To get 2D array you need to use an optional module such as
NumPy ( http://numpy.scipy.org/ ). Then making 2D arrays is as easy as
>>> from numpy import array
>>> ma = array([[1,2,3],[4,5,6]])
>>> print ma
[[1 2 3]
[4 5 6]]
The Numerical Python" manual at
http://numpy.scipy.org/numpydoc/numdoc.htm is all you need to get
started. As the NumPy home page states, just substitute "numpy" where
you see "numeric" in the code samples in this slightly out of date document.
If you want a "2D list", read on.
To build a list that's probably what you
would call a '1D list', you basically have 2 choices:
-- initially bind a variable to an empty list, then append to it:
-- bind the variable right off to a list of the proper length,
then assign to each element
I.e., either use the style:
ar=[]
for i in range(5):
ar.append(i)
or:
ar=[None]*5
for i in range(5):
ar[i]=i
Of course, for this particular case you can also simply
ar=range(5)
or, in Python 2:
ar=[i for i in range(5)]
i.e. bind the variable to a pre-constructed list in some way
or other (the second form is called 'list comprehension').
So, when you go '2-D', you have the same choices; and you can use a
different one on each axis, if you wish, so the
possibilities are many. From the simplest/verbosest...:
arr=[]
for i in range(5):
arr.append([])
for j in range(10):
arr[i].append(i*j)
to the most concise, a nested list comprehension (only in Python 2...!):
arr=[ [i*j for j in range(10)] for i in range(5)]