NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
What you will learn
- Explain why a NumPy array is faster than a Python list for numbers
- Create arrays with array, zeros, ones, full, eye, arange and linspace
- Read shape, ndim, size and dtype, and pick a dtype that saves memory
- Tell a view from a copy and avoid the common silent mistakes
Before you start
- Python lists and loops
- Running a Python file
So far, when you had a lot of numbers, you kept them in a list. NumPy gives you something built only for numbers: the array. The name means numerical Python, and it has one job, working on a lot of numbers at once.
An AI model is mostly numbers in big tables, and training it means multiplying those tables again and again. Plain Python loops are far too slow for that. NumPy does the work in compiled C code, and that's why pandas, Matplotlib and scikit-learn are built on NumPy arrays, and why PyTorch and TensorFlow pass data to and from them so easily.
NumPy doesn't come with Python. The project's requirements.txt has one line, numpy, and every file starts with the same import: import numpy as np. All outputs below are from a real run on NumPy 2.5.4.
Labels and an egg tray
Why is an array so quick? A Python list is like a row of labels. Each label points to a box stored somewhere else in a warehouse. To add the numbers up, you read a label, walk to the box, check what's inside, and come back. For every single item.
An array is more like an egg tray. Every cup is the same size and they all sit side by side in one block. There's nothing to look up, so you go straight along the tray.
One type, one block
Here's that idea in code. np.arange makes a million numbers (more on it in a moment), and the array tells you what it holds.
import numpy as np
arr = np.arange(1_000_000)
print(arr.dtype)
print(arr.itemsize)
print(arr.nbytes)
mixed = np.array([1, "a", 2.5])
print(mixed)
print(mixed.dtype)
nums = np.array([1, 2.5, True])
print(nums)
print(nums.dtype)
int64
8
8000000
['1' 'a' '2.5']
<U32
[1. 2.5 1. ]
float64
Every value is an int64, each takes 8 bytes, so a million of them take exactly 8,000,000 bytes. Nothing extra.
Mix types and NumPy won't keep three of them. With a string in the list, everything becomes text, which is why it prints with quotes. <U32 means text of up to 32 characters. With 1, 2.5 and True, everything can be a float, so True becomes 1.0. An array always holds one type, and if you mix them, NumPy picks one for you.
List against array, timed
import numpy as np
import time
size = 1_000_000
lst = list(range(size))
arr = np.arange(size)
t1 = time.perf_counter()
sum(lst)
list_time = time.perf_counter() - t1
t2 = time.perf_counter()
np.sum(arr)
numpy_time = time.perf_counter() - t2
print(f"List: {list_time:.4f}s")
print(f"NumPy: {numpy_time:.4f}s")
print(f"Speedup: {list_time / numpy_time:.0f}x")
List: 0.0074s
NumPy: 0.0015s
Speedup: 5x
About five times faster on this machine. Your numbers will be different, but the array comes out ahead.
Creating arrays
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.zeros((3, 3))
c = np.ones((2, 4))
d = np.full((3, 3), 7)
print(a)
print(b)
print(c)
print(d)
[1 2 3 4]
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[[7 7 7]
[7 7 7]
[7 7 7]]
np.array turns a list into an array. It prints with spaces and no commas, which is how you tell it apart from a list. np.zeros and np.ones take a shape, rows first, and notice the dots: they give floats by default. np.full takes a shape and a value. Seven is a whole number, so those stay integers. You'll use these to set aside space before you fill it in.
eye, arange and linspace
import numpy as np
e = np.eye(4)
f = np.arange(0, 10, 2)
g = np.linspace(0, 1, 5)
print(e)
print(f)
print(g)
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
[0 2 4 6 8]
[0. 0.25 0.5 0.75 1. ]
np.eye(4) is an identity matrix: ones on the diagonal, zeros everywhere else. np.arange (one r) works like Python's range, and the stop value isn't included. np.linspace is different. You say how many values you want, and both ends are included. So use arange when you know the step and linspace when you know the count.
What an array knows about itself
import numpy as np
arr_1d = np.array([10, 20, 30])
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
arr_3d = np.ones((2, 3, 4))
print("--- 2D Array ---")
print("Shape: ", arr_2d.shape)
print("Ndim: ", arr_2d.ndim)
print("Size: ", arr_2d.size)
print("Dtype: ", arr_2d.dtype)
print("--- 1D and 3D ---")
print(arr_1d.shape, arr_1d.ndim, arr_1d.size)
print(arr_3d.shape, arr_3d.ndim, arr_3d.size)
--- 2D Array ---
Shape: (2, 3)
Ndim: 2
Size: 6
Dtype: int64
--- 1D and 3D ---
(3,) 1 3
(2, 3, 4) 3 24
shape is rows then columns, ndim is the number of dimensions, size is the total count of values. A 1D shape has that little trailing comma, (3,). The 3D array has 2 × 3 × 4 = 24 values. When an array confuses you, print the shape first.
The names you'll hear: a 1D array is a vector, 2D is a matrix, and a stack of matrices is often called a tensor. Each dimension adds one number to the shape and one index. In the lesson's array_dimensions.py, m[1, 2] on a 3 × 3 matrix of 1 to 9 gives 6, and t[1, 0, 1] (layer 1, row 0, column 1) on a 2 × 2 × 2 tensor also gives 6.
Data types and memory
import numpy as np
kinds = [np.int8, np.int16, np.int32, np.int64,
np.float32, np.float64, np.bool_]
for kind in kinds:
dt = np.dtype(kind)
print(f"{dt.name:8} {dt.itemsize} bytes")
print(float(np.float32(0.1)))
print(float(np.float64(0.1)))
int8 1 bytes
int16 2 bytes
int32 4 bytes
int64 8 bytes
float32 4 bytes
float64 8 bytes
bool 1 bytes
0.10000000149011612
0.1
The number in the name is bits, so divide by eight for bytes. Smaller isn't free, though. 0.1 stored as float32 comes back slightly off; float64 keeps enough digits to print as 0.1. Choose the smallest type that's still accurate enough for your data.
You set the type with dtype= and convert with astype, which returns a new array:
import numpy as np
a = np.array([1, 2, 3], dtype=np.float32)
print(a)
print(a.dtype)
b = a.astype(np.int32)
print(b)
print(b.dtype)
c = np.array([True, False, True])
print(c.dtype)
f32 = np.zeros(1000, dtype=np.float32)
f64 = np.zeros(1000, dtype=np.float64)
print(f"float32: {f32.nbytes} bytes")
print(f"float64: {f64.nbytes} bytes")
[1. 2. 3.]
float32
[1 2 3]
int32
bool
float32: 4000 bytes
float64: 8000 bytes
Half the memory for the same thousand values. With millions of values, that choice matters.
A NumPy number isn't a Python number
import numpy as np
arr = np.array([10, 20, 30])
first = arr[0]
print(first)
print(repr(first))
print(type(first))
print([arr[0], arr[1]])
print(arr.tolist())
10
np.int64(10)
<class 'numpy.int64'>
[np.int64(10), np.int64(20)]
[10, 20, 30]
Inside a list you see the long form, np.int64(10). That's just how NumPy 2 prints them. If you need plain Python numbers, use tolist().
Vectorized operations
import numpy as np
nums = [1, 2, 3]
print(nums * 2)
print(np.array(nums) * 2)
[1, 2, 3, 1, 2, 3]
[2 4 6]
A list times two repeats the list. An array times two doubles every value, and you didn't write a loop. That's a vectorized operation. The loop still happens, but in C, over one block of memory. On a million values, the lesson timed a list comprehension at 0.0469 s and arr * 2 at 0.0030 s, roughly fifteen times faster. So before you write a loop over numbers, check whether NumPy can do it in one line.
Same array, or a copy
This one catches almost everyone.
import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = a
b[0] = 99
print(a)
print(b is a)
a = np.array([1, 2, 3, 4, 5])
c = a.copy()
c[0] = 99
print(a)
print(c)
print(np.shares_memory(a, c))
[99 2 3 4 5]
True
[1 2 3 4 5]
[99 2 3 4 5]
False
b = a makes no new array. b is a second name for the same one, so changing b changes a. a.copy() gives c its own block of memory.
A slice is a view
With a list, a slice is a new list. With NumPy, a[1:3] is a view: a window onto the same memory, so a big array isn't copied every time you slice it.
import numpy as np
a = np.array([1, 2, 3, 4, 5])
d = a[1:3]
d[0] = 77
print(a)
print(np.shares_memory(a, d))
e = a[1:3].copy()
e[0] = 0
print(a)
print(np.shares_memory(a, e))
[ 1 77 3 4 5]
True
[ 1 77 3 4 5]
False
.copy() when you want to change it without touching the original.Common mistakes
import numpy as np
mixed = np.array([1, 2, 3.5])
print(mixed.dtype)
a = np.array([10, 20, 30, 40])
b = a[1:3]
b[0] = 999
print(a)
a = np.array([10, 20, 30, 40])
b = a[1:3].copy()
b[0] = 999
print(a)
whole = np.array([1, 2, 3])
whole[0] = 9.7
print(whole)
print(np.array([1.9, 2.7]).astype(int))
small = np.array([200], dtype=np.uint8)
print(small + 100)
float64
[ 10 999 30 40]
[10 20 30 40]
[9 2 3]
[1 2]
[44]
- One float in the list makes the whole array
float64. - Writing through a slice changes the original. With
.copy()it doesn't. - Integer arrays drop decimals with no warning:
9.7becomes9, andastype(int)cuts1.9to1. It cuts, it doesn't round. - Small types overflow quietly. A
uint8only goes up to 255, so 200 + 100 wraps around to 44.
When a number looks wrong, check the dtype.
Rows of different lengths
This mistake does raise an error:
import numpy as np
rows = [[1, 2, 3], [4, 5]]
grid = np.array(rows)
print(grid)
Traceback (most recent call last):
File "S05L01_NumPy\ragged_error.py", line 4, in <module>
grid = np.array(rows)
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.
Read the last line. "Inhomogeneous shape" means your rows aren't the same length. An array has to be a full rectangle.
Recap
| Idea | What to remember |
|---|---|
| Array | One type, one block of memory, so vectorized code runs fast |
| Create | array, zeros, ones, full, eye, arange (step), linspace (count) |
| Inspect | shape, ndim, size, dtype, nbytes |
| dtype | Smallest type that's accurate enough; watch for cut decimals and overflow |
| Views | b = a and slices share memory; .copy() doesn't |
Try it yourself: make a million ones in float32 and in float64 and compare their nbytes. Or ask an AI tool to write it, then read every line it gives you.
If you want the fast tour of NumPy and pandas together, from an AI engineer's point of view, see NumPy and pandas for AI Engineers. Next in this series: indexing, slicing and iterating.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
NumPy Shapes: reshape, transpose, stack, concatenate and split
Change the shape of a NumPy array without changing its data: reshape and -1, transpose, newaxis and squeeze, then stack, concatenate and split, with the errors you get when shapes don't fit.
