IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
5.1 Getting and Setting array values


5.1 Getting and Setting array values

Just like other Python sequences, array contents are manipulated with the [] notation. For rank-1 arrays, there are no differences between list and array notations:

>>> a = arange(10)
>>> print a[0]                          # get first element
0
>>> print a[1:5]                        # get second through fifth elements
[1 2 3 4]
>>> print a[-1]                         # get last element
9
>>> print a[:-1]                        # get all but last element
[0 1 2 3 4 5 6 7 8]
If an array is multidimensional (of rank > 1), then specifying a single integer index will return an array of dimension one less than the original array.

>>> a = arange(9, shape=(3,3))
>>> print a
[[0 1 2]
 [3 4 5]
 [6 7 8]]
>>> print a[0]                          # get first row, not first element!
[0 1 2]
>>> print a[1]                          # get second row
[3 4 5]
To get to individual elements in a rank-2 array, one specifies both indices separated by commas:
>>> print a[0,0]                        # get element at first row, first column
0
>>> print a[0,1]                        # get element at first row, second column
1
>>> print a[1,0]                        # get element at second row, first column
3
>>> print a[2,-1]                       # get element at third row, last column
8
Of course, the [] notation can be used to set values as well:
>>> a[0,0] = 123
>>> print a
[[123   1   2]
 [  3   4   5]
 [  6   7   8]]
Note that when referring to rows, the right hand side of the equal sign needs to be a sequence which ``fits'' in the referred array subset, as described by the broadcast rule (in the code sample below, a 3-element row):
>>> a[1] = [10,11,12] ; print a
[[123   1   2]
 [ 10  11  12]
 [  6   7   8]]
>>> a[2] = 99 ; print a
[[123   1   2]
 [ 10  11  12]
 [ 99  99  99]]

Note also that when assigning floating point values to integer arrays that the values are silently truncated:

>>> a[1] = 93.999432
[[123   1   2]
 [ 93  93  93]
 [ 99  99  99]]

Send comments to the NumArray community.