np.array() from Lists
Create 1D, 2D and 3D arrays from Python lists with np.array(), understand how NumPy picks a dtype (type promotion), and avoid the ragged-list error.
NumPy arrays can be created in two ways: from existing data (convert a Python list you already have) or from scratch (let NumPy generate the values — zeros, ranges, etc.). This topic covers the first, and most common, way: np.array(). You will use it every time you type in a team's scores by hand.
Definition
np.array(object, dtype=None)creates a new ndarray from any array-like Python object — a list, a tuple, a nested list, or another array. The nesting depth of the input decides the number of dimensions, and NumPy chooses one dtype that can represent every element (this is called type promotion).
- Array-like — anything NumPy can turn into an array: lists, tuples,
rangeobjects, nested lists, other arrays. - Nesting depth — a flat list gives a 1D array; a list of lists gives 2D; a list of lists of lists gives 3D.
- Type promotion — if the input mixes kinds, NumPy picks the "widest" kind that fits all:
bool → int → float → complex → string.
Syntax
python
np.array(object, dtype=None, *, copy=True, ndmin=0)| Parameter | Meaning | Default |
|---|---|---|
object | The list / tuple / nested list / array to convert | required |
dtype | Force a data type: int, float, bool, "int32", np.float32 … | None → inferred from the data |
copy | True: always copy the data. (Use np.asarray(x) to avoid copying when x is already an array.) | True |
ndmin | Minimum number of dimensions; extra dimensions of size 1 are added in front | 0 |
Example — 1D, 2D and 3D arrays
python
import numpy as np
# 1D: one batter, 5 matches
virat = np.array([72, 45, 88, 31, 64])
print(virat)
print("ndim:", virat.ndim, "shape:", virat.shape)
print()
# 2D: 3 batters x 4 matches
team = np.array([
[72, 45, 88, 31],
[56, 0, 74, 88],
[45, 32, 0, 67],
])
print(team)
print("ndim:", team.ndim, "shape:", team.shape)
print()
seasons = np.array([
[[72, 45], [56, 0]],
[[65, 80], [39, 55]],
])
print(seasons)
print("ndim:", seasons.ndim, "shape:", seasons.shape)text
[72 45 88 31 64]
ndim: 1 shape: (5,)
[[72 45 88 31]
[56 0 74 88]
[45 32 0 67]]
ndim: 2 shape: (3, 4)
[[[72 45]
[56 0]]
[[65 80]
[39 55]]]
ndim: 3 shape: (2, 2, 2)How it works: count the opening brackets at the start of the printed array — [ = 1D, [[ = 2D, [[[ = 3D. In the 2D case each inner list becomes a row. In the 3D case each 2D block (a season) is printed separately with a blank line between blocks.
Example — type promotion
python
import numpy as np
print(np.array([72, 45, 88]).dtype)
print(np.array([72, 45.5, 88]))
print(np.array([72, 45.5, 88]).dtype)
print(np.array([True, 2, 3]))
print(np.array([True, 2, 3]).dtype)
print(np.array([True, False]).dtype)
print(np.array([1, 2.5, 3+4j]))
print(np.array([72, "Virat"]))
print(np.array([72, "Virat"]).dtype)
print(np.array((10, 20, 30)))
print(np.array(range(5)))text
int64
[72. 45.5 88. ]
float64
[1 2 3]
int64
bool
[1. +0.j 2.5+0.j 3. +4.j]
['72' 'Virat']
<U21
[10 20 30]
[0 1 2 3 4]How it works:
| Input contains | Resulting dtype | Example |
|---|---|---|
| only ints | int64 | [72, 45, 88] |
| ints + at least one float | float64 (ints become 72.) | [72, 45.5, 88] |
| bools + ints | int64 (True → 1) | [True, 2, 3] |
| only bools | bool | [True, False] |
| any complex number | complex128 | [1, 2.5, 3+4j] |
| any string | Unicode string <U.. (numbers become text!) | [72, "Virat"] |
Tuples and range objects work just like lists.
Example — forcing a dtype, ndmin, and copying
python
import numpy as np
a = np.array([72, 45, 88], dtype=float)
print(a)
b = np.array([72.9, 45.2, 88.6], dtype=int)
print(b)
c = np.array([1, 2, 3], ndmin=2)
print(c, c.shape)
lst = [1, 2, 3]
d = np.array(lst)
d[0] = 100
print(lst, d)
print(np.array(5), np.array(5).ndim, np.array(5).shape)text
[72. 45. 88.]
[72 45 88]
[[1 2 3]] (1, 3)
[1, 2, 3] [100 2 3]
5 0 ()How it works:
dtype=floatturns whole numbers into floats.dtype=inton decimals truncates (72.9 → 72, not 73). Round first withnp.roundif you want rounding.ndmin=2wraps the 1D data into a 1×3 2D array.np.arraycopies — changingddoes not touchlst.np.array(5)is a 0-dimensional array (a scalar wrapped in an array) with shape().
The ragged-list error
Every row of a 2D array must have the same length. NumPy refuses "ragged" (uneven) nested lists:
python
import numpy as np
try:
np.array([[1, 2, 3], [4, 5]])
except ValueError as e:
print("ValueError:", e)text
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.Fix: make every row the same length (pad missing matches with 0 or np.nan). Passing dtype=object "works" but gives an array of Python lists with none of NumPy's speed — avoid it.
Common mistakes
- ❌
np.array(1, 2, 3)— values as separate arguments (2is then read as the dtype → error). ✅np.array([1, 2, 3]). - ❌ Rows of different lengths. ✅ Every inner list must have the same number of items.
- ❌ Expecting
dtype=intto round. ✅ It truncates toward zero; usenp.round(x).astype(int)to round. - ❌ One text value in numeric data turning the whole array into strings. ✅ Clean the data or convert with
.astype(int)/.astype(float).
Interview tip
Q: What is the dtype of np.array([1, 2, 3.0]) and why?
A: float64. NumPy needs one common type; since one element is a float, all elements are promoted (upcast) to float so no information is lost.
Key points to remember
- np.array(object) converts a list/tuple/nested list into a new ndarray (it copies the data).
- The nesting depth decides the dimensions: list → 1D, list of lists → 2D, list of lists of lists → 3D.
- Type promotion picks one dtype for all elements: bool → int → float → complex → string.
- dtype= forces a type; converting floats to int truncates (72.9 → 72).
- All rows must have the same length — ragged lists raise a ValueError (inhomogeneous shape).
- np.array(5) is a 0-D array with shape (); ndmin= adds leading dimensions of size 1.
Try it yourself
1D, 2D and 3D from nested lists
Type promotion and forcing a dtype
The ragged-list error
Practice: build the squad table
Revision Flashcards
Tap a card to flip it and see the answer.
