User guide
NumPy User Guide, Release 1.9.0
array([ 0, 10, 20, 30, 40])
>>> x[np.array([1, 1, 3, 1])] += 1
>>> x
array([ 0, 11, 20, 31, 40])
Where people expect that the 1st location will be incremented by 3. In fact, it will only be incremented by 1. The
reason is because a new array is extracted from the original (as a temporary) containing the values at 1, 1, 3, 1, then
the value 1 is added to the temporary, and then the temporary is assigned back to the original array. Thus the value of
the array at x[1]+1 is assigned to x[1] three times, rather than being incremented 3 times.
2.4.10 Dealing with variable numbers of indices within programs
The index syntax is very powerful but limiting when dealing with a variable number of indices. For example, if you
want to write a function that can handle arguments with various numbers of dimensions without having to write special
case code for each number of possible dimensions, how can that be done? If one supplies to the index a tuple, the tuple
will be interpreted as a list of indices. For example (using the previous definition for the array z):
>>> indices = (1,1,1,1)
>>> z[indices]
40
So one can use code to construct tuples of any number of indices and then use these within an index.
Slices can be specified within programs by using the slice() function in Python. For example:
>>> indices = (1,1,1,slice(0,2)) # same as [1,1,1,0:2]
>>> z[indices]
array([39, 40])
Likewise, ellipsis can be specified by code by using the Ellipsis object:
>>> indices = (1, Ellipsis, 1) # same as [1,...,1]
>>> z[indices]
array([[28, 31, 34],
[37, 40, 43],
[46, 49, 52]])
For this reason it is possible to use the output from the np.where() function directly as an index since it always returns
a tuple of index arrays.
Because the special treatment of tuples, they are not automatically converted to an array as a list would be. As an
example:
>>> z[[1,1,1,1]] # produces a large array
array([[[[27, 28, 29],
[30, 31, 32], ...
>>> z[(1,1,1,1)] # returns a single value
40
2.5 Broadcasting
See Also:
numpy.broadcast
The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject
to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes.
26 Chapter 2. Numpy basics