The N-dimensional array (ndarray)

An ndarrayopen in new window is a (usually fixed-size) multidimensional container of items of the same type and size. The number of dimensions and items in an array is defined by its shapeopen in new window, which is a tupleopen in new window of N non-negative integers that specify the sizes of each dimension. The type of items in the array is specified by a separate data-type object (dtype), one of which is associated with each ndarray.

As with other container objects in Python, the contents of an ndarrayopen in new window can be accessed and modified by indexing or slicing the array (using, for example, N integers), and via the methods and attributes of the ndarrayopen in new window.

Different ndarraysopen in new window can share the same data, so that changes made in one ndarrayopen in new window may be visible in another. That is, an ndarray can be a “view” to another ndarray, and the data it is referring to is taken care of by the “base” ndarray. ndarrays can also be views to memory owned by Python stringsopen in new window or objects implementing the buffer or array interfaces.


A 2-dimensional array of size 2 x 3, composed of 4-byte integer elements:

>>> x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
>>> type(x)
<type 'numpy.ndarray'>
>>> x.shape
(2, 3)
>>> x.dtype

The array can be indexed using Python container-like syntax:

>>> # The element of x in the *second* row, *third* column, namely, 6.
>>> x[1, 2]

For example slicing can produce views of the array:

>>> y = x[:,1]
>>> y
array([2, 5])
>>> y[0] = 9 # this also changes the corresponding element in x
>>> y
array([9, 5])
>>> x
array([[1, 9, 3],
       [4, 5, 6]])

Constructing arrays

New arrays can be constructed using the routines detailed in Array creation routines, and also by using the low-level ndarrayopen in new window constructor:

ndarrayopen in new window(shape[, dtype, buffer, offset, …])An array object represents a multidimensional, homogeneous array of fixed-size items.

Indexing arrays

Arrays can be indexed using an extended Python slicing syntax, array[selection]. Similar syntax is also used for accessing fields in a structured data typeopen in new window.

Internal memory layout of an ndarray

An instance of class ndarrayopen in new window consists of a contiguous one-dimensional segment of computer memory (owned by the array, or by some other object), combined with an indexing scheme that maps N integers into the location of an item in the block. The ranges in which the indices can vary is specified by the shapeopen in new window of the array. How many bytes each item takes and how the bytes are interpreted is defined by the data-type object associated with the array.

A segment of memory is inherently 1-dimensional, and there are many different schemes for arranging the items of an N-dimensional array in a 1-dimensional block. NumPy is flexible, and ndarrayopen in new window objects can accommodate any strided indexing scheme. In a strided scheme, the N-dimensional index (n_0, n_1, ..., n_{N-1}) corresponds to the offset (in bytes):

from the beginning of the memory block associated with the array. Here, are integers which specify the stridesopen in new window of the array. The column-majoropen in new window order (used, for example, in the Fortran language and in Matlab) and row-majoropen in new window order (used in C) schemes are just specific kinds of strided scheme, and correspond to memory that can be addressed by the strides:

where d_j = self.shape[j].

Both the C and Fortran orders are contiguousopen in new window, i.e., single-segment, memory layouts, in which every part of the memory block can be accessed by some combination of the indices.

While a C-style and Fortran-style contiguous array, which has the corresponding flags set, can be addressed with the above strides, the actual strides may be different. This can happen in two cases:

  1. If self.shape[k] == 1 then for any legal index index[k] == 0. This means that in the formula for the offset and thus and the value of = self.strides[k] is arbitrary.
  2. If an array has no elements (self.size == 0) there is no legal index and the strides are never used. Any array with no elements may be considered C-style and Fortran-style contiguous.

Point 1. means that self and self.squeeze() always have the same contiguity and aligned flags value. This also means that even a high dimensional array could be C-style and Fortran-style contiguous at the same time.

An array is considered aligned if the memory offsets for all elements and the base offset itself is a multiple of self.itemsize. Understanding memory-alignment leads to better performance on most hardware.


Points (1) and (2) are not yet applied by default. Beginning with NumPy 1.8.0, they are applied consistently only if the environment variable NPY_RELAXED_STRIDES_CHECKING=1 was defined when NumPy was built. Eventually this will become the default.

You can check whether this option was enabled when your NumPy was built by looking at the value of np.ones((10,1), order='C').flags.f_contiguous. If this is True, then your NumPy has relaxed strides checking enabled.


It does not generally hold that self.strides[-1] == self.itemsize for C-style contiguous arrays or self.strides[0] == self.itemsize for Fortran-style contiguous arrays is true.

Data in new ndarraysopen in new window is in the row-majoropen in new window (C) order, unless otherwise specified, but, for example, basic array slicing often produces viewsopen in new window in a different scheme.


Several algorithms in NumPy work on arbitrarily strided arrays. However, some algorithms require single-segment arrays. When an irregularly strided array is passed in to such algorithms, a copy is automatically made.

Array attributes

Array attributes reflect information that is intrinsic to the array itself. Generally, accessing an array through its attributes allows you to get and sometimes set intrinsic properties of the array without creating a new array. The exposed attributes are the core parts of an array and only some of them can be reset meaningfully without creating a new array. Information on each attribute is given below.

Memory layout

The following attributes contain information about the memory layout of the array:

ndarray.flagsopen in new windowInformation about the memory layout of the array.
ndarray.shapeopen in new windowTuple of array dimensions.
ndarray.stridesopen in new windowTuple of bytes to step in each dimension when traversing an array.
ndarray.ndimopen in new windowNumber of array dimensions.
ndarray.dataopen in new windowPython buffer object pointing to the start of the array’s data.
ndarray.sizeopen in new windowNumber of elements in the array.
ndarray.itemsizeopen in new windowLength of one array element in bytes.
ndarray.nbytesopen in new windowTotal bytes consumed by the elements of the array.
ndarray.baseopen in new windowBase object if memory is from some other object.

Data type

The data type object associated with the array can be found in the dtypeopen in new window attribute:

ndarray.dtypeopen in new windowData-type of the array’s elements.

Other attributes

ndarray.Topen in new windowThe transposed array.
ndarray.realopen in new windowThe real part of the array.
ndarray.imagopen in new windowThe imaginary part of the array.
ndarray.flatopen in new windowA 1-D iterator over the array.
ndarray.ctypesopen in new windowAn object to simplify the interaction of the array with the ctypes module.

Array interface

__array_interface__Python-side of the array interface
__array_struct__C-side of the array interface

ctypes foreign function interface

ndarray.ctypesopen in new windowAn object to simplify the interaction of the array with the ctypes module.

Array methods

An ndarrayopen in new window object has many methods which operate on or with the array in some fashion, typically returning an array result. These methods are briefly explained below. (Each method’s docstring has a more complete description.)

For the following methods there are also corresponding functions in numpy: allopen in new window, anyopen in new window, argmaxopen in new window, argminopen in new window, argpartitionopen in new window, argsortopen in new window, chooseopen in new window, clipopen in new window, compressopen in new window, copyopen in new window, cumprodopen in new window, cumsumopen in new window, diagonalopen in new window, imagopen in new window, maxopen in new window, meanopen in new window, minopen in new window, nonzeroopen in new window, partitionopen in new window, prodopen in new window, ptpopen in new window, putopen in new window, ravelopen in new window, realopen in new window, repeatopen in new window, reshapeopen in new window, roundopen in new window, searchsortedopen in new window, sortopen in new window, squeezeopen in new window, stdopen in new window, sumopen in new window, swapaxesopen in new window, takeopen in new window, traceopen in new window, transposeopen in new window, varopen in new window.

Array conversion

ndarray.itemopen in new window(*args)Copy an element of an array to a standard Python scalar and return it.
ndarray.tolistopen in new window()Return the array as an a.ndim-levels deep nested list of Python scalars.
ndarray.itemsetopen in new window(*args)Insert scalar into an array (scalar is cast to array’s dtype, if possible)
ndarray.tostringopen in new window([order])Construct Python bytes containing the raw data bytes in the array.
ndarray.tobytesopen in new window([order])Construct Python bytes containing the raw data bytes in the array.
ndarray.tofileopen in new window(fid[, sep, format])Write array to a file as text or binary (default).
ndarray.dumpopen in new window(file)Dump a pickle of the array to the specified file.
ndarray.dumpsopen in new window()Returns the pickle of the array as a string.
ndarray.astypeopen in new window(dtype[, order, casting, …])Copy of the array, cast to a specified type.
ndarray.byteswapopen in new window([inplace])Swap the bytes of the array elements
ndarray.copyopen in new window([order])Return a copy of the array.
ndarray.viewopen in new window([dtype, type])New view of array with the same data.
ndarray.getfieldopen in new window(dtype[, offset])Returns a field of the given array as a certain type.
ndarray.setflagsopen in new window([write, align, uic])Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively.
ndarray.fillopen in new window(value)Fill the array with a scalar value.

Shape manipulation

For reshape, resize, and transpose, the single tuple argument may be replaced with n integers which will be interpreted as an n-tuple.

ndarray.reshapeopen in new window(shape[, order])Returns an array containing the same data with a new shape.
ndarray.resizeopen in new window(new_shape[, refcheck])Change shape and size of array in-place.
ndarray.transposeopen in new window(*axes)Returns a view of the array with axes transposed.
ndarray.swapaxesopen in new window(axis1, axis2)Return a view of the array with axis1 and axis2 interchanged.
ndarray.flattenopen in new window([order])Return a copy of the array collapsed into one dimension.
ndarray.ravelopen in new window([order])Return a flattened array.
ndarray.squeezeopen in new window([axis])Remove single-dimensional entries from the shape of a.

Item selection and manipulation

For array methods that take an axis keyword, it defaults to None. If axis is None, then the array is treated as a 1-D array. Any other value for axis represents the dimension along which the operation should proceed.

ndarray.takeopen in new window(indices[, axis, out, mode])Return an array formed from the elements of a at the given indices.
ndarray.putopen in new window(indices, values[, mode])Set a.flat[n] = values[n] for all n in indices.
ndarray.repeatopen in new window(repeats[, axis])Repeat elements of an array.
ndarray.chooseopen in new window(choices[, out, mode])Use an index array to construct a new array from a set of choices.
ndarray.sortopen in new window([axis, kind, order])Sort an array in-place.
ndarray.argsortopen in new window([axis, kind, order])Returns the indices that would sort this array.
ndarray.partitionopen in new window(kth[, axis, kind, order])Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.
ndarray.argpartitionopen in new window(kth[, axis, kind, order])Returns the indices that would partition this array.
ndarray.searchsortedopen in new window(v[, side, sorter])Find indices where elements of v should be inserted in a to maintain order.
ndarray.nonzeroopen in new window()Return the indices of the elements that are non-zero.
ndarray.compressopen in new window(condition[, axis, out])Return selected slices of this array along given axis.
ndarray.diagonalopen in new window([offset, axis1, axis2])Return specified diagonals.


Many of these methods take an argument named axis. In such cases,

  • If axis is None (the default), the array is treated as a 1-D array and the operation is performed over the entire array. This behavior is also the default if self is a 0-dimensional array or array scalar. (An array scalar is an instance of the types/classes float32, float64, etc., whereas a 0-dimensional array is an ndarray instance containing precisely one array scalar.)
  • If axis is an integer, then the operation is done over the given axis (for each 1-D subarray that can be created along the given axis).

A 3-dimensional array of size 3 x 3 x 3, summed over each of its three axes

>>> x
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],
       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],
       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])
>>> x.sum(axis=0)
array([[27, 30, 33],
       [36, 39, 42],
       [45, 48, 51]])
>>> # for sum, axis is the first keyword, so we may omit it,
>>> # specifying only its value
>>> x.sum(0), x.sum(1), x.sum(2)
(array([[27, 30, 33],
        [36, 39, 42],
        [45, 48, 51]]),
 array([[ 9, 12, 15],
        [36, 39, 42],
        [63, 66, 69]]),
 array([[ 3, 12, 21],
        [30, 39, 48],
        [57, 66, 75]]))

The parameter dtype specifies the data type over which a reduction operation (like summing) should take place. The default reduce data type is the same as the data type of self. To avoid overflow, it can be useful to perform the reduction using a larger data type.

For several methods, an optional out argument can also be provided and the result will be placed into the output array given. The out argument must be an ndarrayopen in new window and have the same number of elements. It can have a different data type in which case casting will be performed.

ndarray.maxopen in new window([axis, out, keepdims, initial, …])Return the maximum along a given axis.
ndarray.argmaxopen in new window([axis, out])Return indices of the maximum values along the given axis.
ndarray.minopen in new window([axis, out, keepdims, initial, …])Return the minimum along a given axis.
ndarray.argminopen in new window([axis, out])Return indices of the minimum values along the given axis of a.
ndarray.ptpopen in new window([axis, out, keepdims])Peak to peak (maximum - minimum) value along a given axis.
ndarray.clipopen in new window([min, max, out])Return an array whose values are limited to [min, max].
ndarray.conjopen in new window()Complex-conjugate all elements.
ndarray.roundopen in new window([decimals, out])Return a with each element rounded to the given number of decimals.
ndarray.traceopen in new window([offset, axis1, axis2, dtype, out])Return the sum along diagonals of the array.
ndarray.sumopen in new window([axis, dtype, out, keepdims, …])Return the sum of the array elements over the given axis.
ndarray.cumsumopen in new window([axis, dtype, out])Return the cumulative sum of the elements along the given axis.
ndarray.meanopen in new window([axis, dtype, out, keepdims])Returns the average of the array elements along given axis.
ndarray.varopen in new window([axis, dtype, out, ddof, keepdims])Returns the variance of the array elements, along given axis.
ndarray.stdopen in new window([axis, dtype, out, ddof, keepdims])Returns the standard deviation of the array elements along given axis.
ndarray.prodopen in new window([axis, dtype, out, keepdims, …])Return the product of the array elements over the given axis
ndarray.cumprodopen in new window([axis, dtype, out])Return the cumulative product of the elements along the given axis.
ndarray.allopen in new window([axis, out, keepdims])Returns True if all elements evaluate to True.
ndarray.anyopen in new window([axis, out, keepdims])Returns True if any of the elements of a evaluate to True.

Arithmetic, matrix multiplication, and comparison operations

Arithmetic and comparison operations on ndarraysopen in new window are defined as element-wise operations, and generally yield ndarrayopen in new window objects as results.

Each of the arithmetic operations (+, -, *, /, //, %, divmod(), ** or pow(), <<, >>, &, ^, |, ~) and the comparisons (==, <, >, <=, >=, !=) is equivalent to the corresponding universal function (or ufuncopen in new window for short) in NumPy. For more information, see the section on Universal Functions.

Comparison operators:

ndarray._lt_open in new window(self, value, /)Return self<value.
ndarray._le_open in new window(self, value, /)Return self<=value.
ndarray._gt_open in new window(self, value, /)Return self>value.
ndarray._ge_open in new window(self, value, /)Return self>=value.
ndarray._eq_open in new window(self, value, /)Return self==value.
ndarray._ne_open in new window(self, value, /)Return self!=value.

Truth value of an array (bool):

ndarray.__bool__open in new window(self, /)self != 0


Truth-value testing of an array invokes ndarray.__bool__open in new window, which raises an error if the number of elements in the array is larger than 1, because the truth value of such arrays is ambiguous. Use .any()open in new window and .all()open in new window instead to be clear about what is meant in such cases. (If the number of elements is 0, the array evaluates to False.)

Unary operations:

ndarray.__neg__open in new window(self, /)-self
ndarray.__pos__open in new window(self, /)+self
ndarray.__abs__open in new window(self)
ndarray.__invert__open in new window(self, /)~self


ndarray.__add__open in new window(self, value, /)Return self+value.
ndarray.__sub__open in new window(self, value, /)Return self-value.
ndarray.__mul__open in new window(self, value, /)Return self*value.
ndarray.__truediv__open in new window(self, value, /)Return self/value.
ndarray.__floordiv__open in new window(self, value, /)Return self//value.
ndarray.__mod__open in new window(self, value, /)Return self%value.
ndarray.__divmod__open in new window(self, value, /)Return divmod(self, value).
ndarray.__pow__open in new window(self, value[, mod])Return pow(self, value, mod).
ndarray.__lshift__open in new window(self, value, /)Return self<<value.
ndarray.__rshift__open in new window(self, value, /)Return self>>value.
ndarray.__and__open in new window(self, value, /)Return self&value.
ndarray.__or__open in new window(self, value, /)Return self
ndarray.__xor__open in new window(self, value, /)Return self^value.


Arithmetic, in-place:

ndarray.__iadd__open in new window(self, value, /)Return self+=value.
ndarray.__isub__open in new window(self, value, /)Return self-=value.
ndarray.__imul__open in new window(self, value, /)Return self*=value.
ndarray.__itruediv__open in new window(self, value, /)Return self/=value.
ndarray.__ifloordiv__open in new window(self, value, /)Return self//=value.
ndarray.__imod__open in new window(self, value, /)Return self%=value.
ndarray.__ipow__open in new window(self, value, /)Return self**=value.
ndarray.__ilshift__open in new window(self, value, /)Return self<<=value.
ndarray.__irshift__open in new window(self, value, /)Return self>>=value.
ndarray.__iand__open in new window(self, value, /)Return self&=value.
ndarray.__ior__open in new window(self, value, /)Return self
ndarray.__ixor__open in new window(self, value, /)Return self^=value.


In place operations will perform the calculation using the precision decided by the data type of the two operands, but will silently downcast the result (if necessary) so it can fit back into the array. Therefore, for mixed precision calculations, A {op}= B can be different than A = A {op} B. For example, suppose a = ones((3,3)). Then, a += 3j is different than a = a + 3j: while they both perform the same computation, a += 3 casts the result to fit back in a, whereas a = a + 3j re-binds the name a to the result.

Matrix Multiplication:

ndarray.__matmul__open in new window(self, value, /)Return self@value.


Matrix operators @ and @= were introduced in Python 3.5 following PEP465. NumPy 1.10.0 has a preliminary implementation of @ for testing purposes. Further documentation can be found in the matmulopen in new window documentation.

Special methods

For standard library functions:

ndarray.__copy__open in new window()Used if copy.copyopen in new window is called on an array.
ndarray.__deepcopy__open in new window()Used if copy.deepcopyopen in new window is called on an array.
ndarray.__reduce__open in new window()For pickling.
ndarray.__setstate__open in new window(state, /)For unpickling.

Basic customization:

ndarray.__new__open in new window(*args, **kwargs)Create and return a new object.
ndarray.__array__open in new window()Returns either a new reference to self if dtype is not given or a new array of provided data type if dtype is different from the current dtype of the array.
ndarray.__array_wrap__open in new window()

Container customization: (see Indexing)

ndarray.__len__open in new window(self, /)Return len(self).
ndarray.__getitem__open in new window(self, key, /)Return self[key].
ndarray.__setitem__open in new window(self, key, value, /)Set self[key] to value.
ndarray.__contains__open in new window(self, key, /)Return key in self.

Conversion; the operations int, float and complex. . They work only on arrays that have one element in them and return the appropriate scalar.

ndarray.__int__open in new window(self)none
ndarray.__float__open in new window(self)none
ndarray.__complex__open in new window()none

String representations:

ndarray.__str__open in new window(self, /)Return str(self).
ndarray.__repr__open in new window(self, /)Return repr(self).