NumPy: Creating Arrays
Last updated: 2026-08-26
Creating Arrays
1. What You'll Learn
- ❶ Creating from Python objects
- ❷ Numeric sequences (arange / linspace / logspace)
- ❸ Pre-filled arrays (zeros / ones / eye / full)
- ❹ Random number generation
- ❺ Reading from files
2. Story
Charlie needs 100 evenly spaced angles from 0 to 2π. Python loop: 5 lines. np.linspace: 1 line.
linspace(0, 2*pi, 100)means "take 100 evenly spaced points from 0 to 2π" — code is documentation.
3. Key Concepts
(1) Creating from Python Objects
The most basic approach — converting Python lists (or nested lists) to NumPy arrays:
import numpy as np
a = np.array([1, 2, 3]) # 1D from list
b = np.array([[1, 2], [3, 4]]) # 2D from nested list
c = np.array([1, 2, 3], dtype=float) # specify dtype
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
Creation Methods Comparison
| Method | Syntax | Input Source | Typical Use |
|---|---|---|---|
np.array |
np.array(obj) |
Python list/tuple | Converting existing data |
np.arange |
np.arange(start, stop, step) |
Numeric range | Integer/float sequences |
np.linspace |
np.linspace(a, b, n) |
Start, stop, count | Precise element count |
np.zeros |
np.zeros(shape) |
Shape | Initialize all zeros |
np.ones |
np.ones(shape) |
Shape | Initialize all ones |
np.full |
np.full(shape, val) |
Shape + fill value | Initialize to any value |
np.random.rand |
np.random.rand(n) |
Element count | Random initialization |
np.fromfunction |
np.fromfunction(fn, shape) |
Function + shape | Generate by formula |
(2) Numeric Sequences
arange
np.arange(5) # [0 1 2 3 4]
np.arange(1, 10, 2) # [1 3 5 7 9]
np.arange(0, 1, 0.3) # [0. 0.3 0.6 0.9]
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
linspace
np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1. ]
np.linspace(0, 2*np.pi, 100) # 100 points from 0 to 2pi
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
logspace
np.logspace(1, 3, 3) # [ 10. 100. 1000.] -- 10^1, 10^2, 10^3
np.logspace(0, 2, 5) # 5 points from 10^0 to 10^2
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
arange vs linspace vs logspace
| Feature | arange |
linspace |
logspace |
|---|---|---|---|
| Control | start, stop, step | start, stop, num | start_exp, stop_exp, num |
| Includes stop | No | Yes | Yes |
| Spacing | Linear | Linear | Logarithmic |
| Float precision | Can have errors | Exact | Exact |
| Typical use | Integer indices | Plotting samples | Frequency/log scales |
(3) Pre-filled Arrays
np.zeros(3) # [0. 0. 0.]
np.zeros((2, 3)) # 2x3 zero matrix
np.ones((2, 2)) # 2x2 ones
np.eye(3) # 3x3 identity
np.full((2, 3), 7) # 2x3 filled with 7
np.empty((2, 2)) # 2x2 uninitialized (NOT zeros!)
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
zeros vs empty vs full
| Function | Initial Value | Speed | Safety | Use Case |
|---|---|---|---|---|
zeros |
All zeros | Medium | Safe | Need a known initial value |
empty |
Undefined | Fast | Unsafe | Overwriting all elements immediately |
full |
Custom value | Medium | Safe | Need a non-zero initial value |
(4) Random Number Creation
np.random.rand(3) # 3 uniform [0, 1)
np.random.rand(2, 3) # 2x3 uniform
np.random.randn(3) # 3 standard normal
np.random.randint(0, 10, 5) # 5 ints in [0, 10)
np.random.seed(42) # set seed for reproducibility
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
Random Function Quick Reference
| Function | Distribution | Range | Return Type |
|---|---|---|---|
rand(d0, d1, ...) |
Uniform | [0, 1) | float |
randn(d0, d1, ...) |
Standard normal | (-∞, +∞) | float |
randint(low, high, size) |
Uniform integer | [low, high) | int |
uniform(low, high, size) |
Uniform | [low, high) | float |
normal(loc, scale, size) |
Normal | (-∞, +∞) | float |
choice(a, size) |
Discrete uniform | Elements of a | depends |
(5) Reading from Files
data = np.loadtxt('data.txt') # plain text
data = np.loadtxt('data.csv', delimiter=',') # CSV
data = np.genfromtxt('data.csv', delimiter=',', # handle missing
filling_values=0)
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
fromfunction — generate arrays by coordinate function:
np.fromfunction(lambda i, j: i + j, (3, 3))
# [[0. 1. 2.]
# [1. 2. 3.]
# [2. 3. 4.]]
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
▶ Example
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
: arange vs linspace vs logspace (Difficulty ⭐)
import numpy as np
# arange: step-based
a = np.arange(0, 10, 2) # [0 2 4 6 8]
print("arange:", a)
# linspace: num-based
b = np.linspace(0, 10, 6) # 6 points: 0, 2, 4, 6, 8, 10
print("linspace:", b)
# logspace: logarithmic
c = np.logspace(1, 4, 4) # [10, 100, 1000, 10000]
print("logspace:", c)
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
▶ Example
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
: zeros / ones / eye / full (Difficulty ⭐)
import numpy as np
z = np.zeros((2, 3))
print("zeros:\n", z)
o = np.ones((3, 2))
print("ones:\n", o)
e = np.eye(4)
print("eye:\n", e)
f = np.full((2, 3), 9.0)
print("full:\n", f)
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
▶ Example
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
: Nested list to 2D array (Difficulty ⭐)
import numpy as np
data = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
a = np.array(data)
print("shape:", a.shape) # (3, 3)
print("dtype:", a.dtype) # int64
print("ndim:", a.ndim) # 2
print("array:\n", a)
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
▶ Example
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
: Random array generation (Difficulty ⭐)
import numpy as np
np.random.seed(42)
print("rand(3):", np.random.rand(3))
print("randn(3):", np.random.randn(3))
print("randint(0,10,5):", np.random.randint(0, 10, 5))
print("uniform(0,1,3):", np.random.uniform(0, 1, 3))
print("normal(0,1,3):", np.random.normal(0, 1, 3))
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
4. Comparison Tables
(1) Creation Method by Use Case
| Need | Method | Why |
|---|---|---|
| Convert existing data | np.array(data) |
Direct conversion |
| Integer sequence | np.arange(n) |
Lightweight |
| Precise floating sequence | np.linspace(a, b, n) |
Exact count |
| Fixed value matrix | np.full(shape, val) |
Any fill value |
| Identity matrix | np.eye(n) |
Linear algebra |
| Random initialization | np.random.rand(...) |
ML weights |
| Load from file | np.loadtxt(file) |
External data |
(2) arange vs Python range
| Feature | range |
np.arange |
|---|---|---|
| Returns | Lazy iterator | ndarray (materialized) |
| Memory | O(1) | O(n) |
| Float step | No | Yes |
| Speed (iteration) | Slower | Faster (vectorized) |
| Use case | Looping | Array creation |
5. Principle Diagram
graph TB
A[Python List] -->|np.array| B[ndarray]
C[arange / linspace] --> B
D[zeros / ones / eye] --> B
E[random functions] --> B
F[file: loadtxt] --> B
B --> G[uniform dtype]
B --> H[contiguous memory]
B --> I[vectorized ops]
❓ FAQ
np.random.default_rng(seed) to create a Generator object, then call .random(), .normal(), .integers(), etc. The old np.random.seed() still works but is considered legacy.np.array(x for x in range(10)) doesn't work — it creates a 0D array containing the generator object. Use np.fromiter((x for x in range(10)), dtype=int) instead.np.genfromtxt('file.csv', delimiter=',', filling_values=0) to replace missing values with a default, or np.nan.📖 Summary
np.array()converts Python lists to ndarrays; dtype is inferred automaticallyarange(start, stop, step)creates evenly spaced sequences;linspacecontrols the countzeros/ones/eye/fullcreate pre-filled arrays;emptyis faster but uninitialized- Random functions:
rand(uniform),randn(normal),randint(integer),choice(sampling) loadtxtandgenfromtxtread arrays from text files;fromfunctiongenerates by formula
📝 Exercises
-
Beginner (Difficulty ⭐): Create the following arrays: (a) integers 0 to 9, (b) 10 evenly spaced points from 0 to 1, (c) a 3x3 identity matrix, (d) a 2x4 array of all 7s.
-
Intermediate (Difficulty ⭐⭐): Use
np.loadtxtto read a CSV file with 3 columns: name (string), age (int), salary (float). Usenp.genfromtxtwithdtype=Noneto handle the mixed types. Print the average salary. -
Advanced (Difficulty ⭐⭐⭐): Benchmark creating 10 million random numbers using
np.random.rand(10_000_000)vs a Python list comprehension. Record the time and memory difference. Then usenp.random.default_rng()and compare the speed.