NumPy Array Creation
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Before any computation there is an array, and NumPy offers a handful of families of functions to build one: from existing Python data, with constant values, with a regular structure (identity, diagonal, triangular), by combining blocks, or from a function or a buffer. This page explains each family, the arguments they share, and what changed in NumPy 2.x. Ranges and coordinate grids have their own page, Ranges and Grids. The page targets NumPy 2.5 and was checked in October 2026. Examples target Python 3.13 or 3.14 and were run on Python 3.13. The examples were run with NumPy 2.5.4 and the output shown is the real one.
Arrays from existing data
np.array
import numpy as np
print(np.array([1, 2, 3]))
print(np.array([1, 2.5]))
print(np.array([1, "a"]).dtype)
print(np.array([[1, 2], [3, 4]], dtype=np.float32))
print(np.array([1, 2, 3], ndmin=2).shape)
Output:
[1 2 3]
[1. 2.5]
<U21
[[1. 2.]
[3. 4.]]
(1, 3)
Source: Array creation and numpy.array.
np.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, ndmax=0, like=None) accepts any nested
sequence or any object that exposes the array interface. The important arguments:
-
dtype: if omitted NumPy chooses the smallest dtype that holds every element (int64for integers,float64as soon as one float appears, a Unicode string dtype such as<U21as soon as a string appears). Integers that do not fitint64giveuint64or anobjectarray. Always passdtypewhen the data type matters, for examplenp.float32for memory-sensitive data. -
ndmin: the minimum number of dimensions; extra axes are prepended, sondmin=2turns a vector into a row(1, n). -
ndmax: new in NumPy 2.4, the maximum number of dimensions to discover; deeper nesting stays as objects (only valid withdtype=object). -
order: memory layout,'C'row-major,'F'column-major or'K'to keep the layout of an input array (see Memory Layout and Strides). -
subok: keep subclasses (such as masked arrays) instead of converting to a basendarray. -
like: create an array of the same array type as the reference object (for example a CuPy array) through__array_function__.
The copy argument changed in NumPy 2.0
np.array copies its input by default (copy=True). Passing copy=False used to mean "avoid the copy if you can". In
NumPy 2 it means "never copy" and raises a ValueError if a copy is needed. The old meaning is copy=None, which is
also what np.asarray does:
import numpy as np
lst = [1, 2, 3]
a = np.array(lst)
b = np.asarray(a) # same object: nothing to convert
c = np.array(a) # new copy
d = np.asarray(a, dtype=float) # dtype differs, so a new array
print(b is a, c is a, np.shares_memory(a, c), d is a)
print(np.array(a, copy=None) is a)
try:
np.array(lst, copy=False) # a list can never be used without a copy
except ValueError as e:
print("ValueError:", str(e).splitlines()[0])
Output:
True False False False
True
ValueError: Unable to avoid copy while creating an array as requested.
Source: NumPy 2.0 migration guide: the copy keyword and numpy.asarray.
The practical rule is to use np.asarray(x) in functions that accept array-like input and do not
modify it, and np.array(x) when you need a private copy that you will modify.
asarray, asanyarray and friends
-
np.asarray(a): returnaitself when it is already an ndarray of the right dtype, otherwise convert. Subclasses such as masked arrays are converted to plainndarray(the mask is lost). -
np.asanyarray(a): likeasarraybut passes subclasses through. -
np.ascontiguousarray(a)andnp.asfortranarray(a): guarantee a C or Fortran contiguous layout, for example before handing memory to compiled code. -
np.copy(a): a copy that, unlikenp.array, does not preserve subclasses by default.
import numpy as np
m = np.ma.array([1, 2], mask=[0, 1])
print(np.asanyarray(m)) # [1 --], masked array kept
print(np.asarray(m)) # [1 2], mask dropped
Output:
[1 --]
[1 2]
Source: numpy.asanyarray.
Ragged input
A nested list whose sub-lists have different lengths cannot become a regular array. Since NumPy 1.24 that is a
ValueError instead of a silent object array:
import numpy as np
try:
np.array([[1, 2], [3]])
except ValueError as e:
print("ValueError:", str(e).split(".")[0])
print(np.array([[1, 2], [3]], dtype=object))
print(np.array([[[1, 2]]], dtype=object, ndmax=2).shape)
Output:
ValueError: setting an array element with a sequence
[list([1, 2]) list([3])]
(1, 1)
Source: Array creation.
An object array is a one-dimensional array of pointers: it gives up most of NumPy’s speed. Prefer padding with np.nan,
a flat array plus offsets, or a pandas or Arrow structure for ragged data.
Arrays with a constant value
import numpy as np
print(np.zeros(3))
print(np.ones((2, 2), dtype=int))
print(np.full(3, np.pi))
print(np.full((2,), 1 + 2j))
e = np.empty(3)
print(e.shape, e.dtype)
Output:
[0. 0. 0.]
[[1 1]
[1 1]]
[3.14159265 3.14159265 3.14159265]
[1.+2.j 1.+2.j]
(3,) float64
-
zeros(shape, dtype=float),ones(shape, dtype=float): the default dtype isfloat64, notint. -
full(shape, fill_value, dtype=None): the dtype is inferred from the fill value, sonp.full(3, 7)is an integer array andnp.full(3, 7.0)a float one. -
empty(shape, dtype=float): allocates memory without writing it. The values are arbitrary leftovers and can look like valid numbers; any read before a full write is a bug. -
shapeis anintor a tuple of ints.np.zeros(2, 3)is an error (the second positional argument is the dtype); writenp.zeros2, 3.
The like variants
import numpy as np
x = np.arange(6).reshape(2, 3)
print(np.zeros_like(x))
print(np.ones_like(x, dtype=float))
print(np.full_like(x, 9))
print(np.empty_like(x).shape)
Output:
[[0 0 0]
[0 0 0]]
[[1. 1. 1.]
[1. 1. 1.]]
[[9 9 9]
[9 9 9]]
(2, 3)
Source: numpy.zeros_like.
zeros_like, ones_like, full_like and empty_like copy shape, dtype and layout from a prototype. The inherited
dtype is a classic pitfall: np.full_like(x, 0.5) on an integer array stores 0. Pass dtype= to override it.
Structured arrays of numbers
eye, identity, diag, vander
import numpy as np
print(np.eye(3))
print(np.eye(3, 4, k=1))
print(np.identity(2))
print(np.diag([1, 2, 3]))
print(np.diag(np.arange(9).reshape(3, 3)))
print(np.diag([1, 2], k=1))
print(np.vander([1, 2, 3], 4))
print(np.vander([1, 2, 3], 3, increasing=True))
Output:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
[[1. 0.]
[0. 1.]]
[[1 0 0]
[0 2 0]
[0 0 3]]
[0 4 8]
[[0 1 0]
[0 0 2]
[0 0 0]]
[[ 1 1 1 1]
[ 8 4 2 1]
[27 9 3 1]]
[[1 1 1]
[1 2 4]
[1 3 9]]
Source: numpy.eye, numpy.diag and numpy.vander.
-
eye(N, M=None, k=0)puts ones on thek-th diagonal;identity(n)is the square,k=0shortcut. -
diag(v, k=0)is two functions in one: given a 1-D array it builds a 2-D array withvon thek-th diagonal; given a 2-D array it extracts thek-th diagonal as a 1-D array. -
vander(x, N=None, increasing=False)builds a Vandermonde matrix whose columns are powers ofx, the design matrix of polynomial least squares. The default order is decreasing powers; passincreasing=Trueto match the ordering ofnumpy.polynomial.
Triangular matrices
import numpy as np
print(np.tri(3))
print(np.tril(np.ones((3, 3))))
print(np.triu(np.ones((3, 3)), k=1))
Output:
[[1. 0. 0.]
[1. 1. 0.]
[1. 1. 1.]]
[[1. 0. 0.]
[1. 1. 0.]
[1. 1. 1.]]
[[0. 1. 1.]
[0. 0. 1.]
[0. 0. 0.]]
Source: numpy.tri.
tri builds a lower-triangular ones matrix; tril and triu zero out the upper or lower part of an existing array,
shifted by k. Non-integer N, M or k values passed to tri and to the tril_indices and triu_indices family
are deprecated in NumPy 2.5.
Assembling arrays from blocks
import numpy as np
print(np.block([[np.eye(2), np.zeros((2, 1))],
[np.zeros((1, 2)), np.ones((1, 1))]]))
Output:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Source: numpy.block.
np.block assembles an array from nested lists of blocks: the innermost list is joined along the last axis, the next
level along the second-to-last, and so on. It is the readable way to write block matrices; np.concatenate,
np.stack, np.vstack and np.hstack are described in
Reshaping, Stacking and Splitting.
Arrays from rules, iterators and bytes
import numpy as np
print(np.fromiter((i * i for i in range(5)), dtype=int))
print(np.frombuffer(b"\x01\x02\x03\x04", dtype=np.uint8))
print(np.fromfunction(lambda i, j: i * 10 + j, (3, 3), dtype=int))
print(np.repeat([1, 2], 2))
print(np.tile([1, 2], (2, 2)))
Output:
[ 0 1 4 9 16]
[1 2 3 4]
[[ 0 1 2]
[10 11 12]
[20 21 22]]
[1 1 2 2]
[[1 2 1 2]
[1 2 1 2]]
Source: numpy.fromiter, numpy.frombuffer and numpy.fromfunction.
-
fromiter(iterable, dtype, count=-1)consumes any iterable into a 1-D array without building an intermediate list; passcountwhen the length is known to preallocate. Thedtypeis mandatory. -
frombuffer(buffer, dtype)wraps existing bytes without copying, so the result is read-only for immutablebytesand shares memory with writable buffers such asbytearray. Use it to view binary data in place. -
fromfunction(function, shape, dtype=float)calls the function once with coordinate arrays (not once per element), so the function must be vectorised. The default dtype of the coordinates is float; passdtype=intfor integer indices. -
repeatrepeats elements;tilerepeats the whole array. Both return new arrays.
The binary mode of np.fromstring is deprecated; use np.frombuffer, and for text use np.loadtxt,
np.genfromtxt or the standard library (see Reading and Writing Files).
Choosing the dtype
import numpy as np
print(np.zeros((2, 2)).dtype, np.zeros(2, dtype="int8").dtype)
print(np.ones(2, dtype=bool))
print(np.zeros(2, dtype=[("x", "f4"), ("n", "i4")]))
m = np.ones((3, 4))
print(m.ndim, m.shape, m.size, m.dtype, m.strides, m.flags.c_contiguous)
Output:
float64 int8
[ True True]
[(0., 0) (0., 0)]
2 (3, 4) 12 float64 (32, 8) True
Source: Data type objects and The N-dimensional array.
Pass dtype as a NumPy type (np.float32), a string ("int8", "f4") or a np.dtype object. A few rules that avoid
most surprises:
-
The default for the constant constructors is
float64; forarangeand for integer input toarrayit is the platform integer,int64on 64-bit systems (also on Windows since NumPy 2.0). -
Use
np.bool(notbool_in new code) for booleans,np.float64rather than the removednp.float_. -
Structured dtypes such as
[("x", "f4"), ("n", "i4")]create record arrays; see Structured Arrays. -
Choose
float32only when memory or a GPU requires it; the lost precision (about seven decimal digits) is rarely worth it in analysis code. See Data Types.
m.strides gives the byte step per axis: (32, 8) for a (3, 4) array of 8-byte floats means moving to the next row
skips 32 bytes and to the next column 8.
Pitfalls summary
-
emptyis not zeros. Reading uninitialised memory produces arbitrary values that may differ between runs. -
A list multiplied by an int is not an array.
np.array([0]) * 3is element-wise;[0] * 3builds a list of three zeros, and[[0] * 3] * 2repeats the same inner list object twice. Build 2-D data withnp.zeros2, 3. -
Dtype inheritance in
_like. The prototype’s dtype wins unlessdtype=is given. -
copy=Falsenow raises. Usenp.asarrayorcopy=Nonefor "copy only if needed". -
Mixed types silently upcast.
np.array([1, "a"])becomes a string array, not an error. -
Large nested Python lists are slow to convert. Create arrays directly with
zeros,arangeorfromiter, or read them from a file, rather than building giant lists first.