NumPy: Creating Arrays

Last updated: 2026-08-26

Creating Arrays

1. What You'll Learn



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:

PYTHON
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
TEXT 📖 Display only
> **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

PYTHON
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]
TEXT 📖 Display only
> **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

PYTHON
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
TEXT 📖 Display only
> **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

PYTHON
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
TEXT 📖 Display only
> **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

PYTHON
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!)
TEXT 📖 Display only
> **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

PYTHON
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
TEXT 📖 Display only
> **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

PYTHON
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)
TEXT 📖 Display only
> **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:

PYTHON
np.fromfunction(lambda i, j: i + j, (3, 3))
# [[0. 1. 2.]
#  [1. 2. 3.]
#  [2. 3. 4.]]
TEXT 📖 Display only
> **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

TEXT 📖 Display only
> **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 ⭐)

PYTHON
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)
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.


▶ Example

TEXT 📖 Display only
> **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 ⭐)

PYTHON
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)
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.


▶ Example

TEXT 📖 Display only
> **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 ⭐)

PYTHON
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)
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.


▶ Example

TEXT 📖 Display only
> **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 ⭐)

PYTHON
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))
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.



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

100%
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

Q What's the difference between arange and linspace?
A arange takes a step size and doesn't include the stop value. linspace takes a count and includes both endpoints. Use arange for integer sequences, linspace when you need a specific number of points.
Q Is empty() really empty?
A No — it allocates the memory but doesn't initialize it. The "values" are whatever was in that memory before. It's faster but dangerous. Only use it when you're about to fill every element.
Q What's the modern way to generate random numbers?
A Use 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.
Q Can I create an array from a generator expression?
A 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.
Q How do I handle missing data when loading CSV?
A Use np.genfromtxt('file.csv', delimiter=',', filling_values=0) to replace missing values with a default, or np.nan.

📖 Summary



📝 Exercises

  1. 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.

  2. Intermediate (Difficulty ⭐⭐): Use np.loadtxt to read a CSV file with 3 columns: name (string), age (int), salary (float). Use np.genfromtxt with dtype=None to handle the mixed types. Print the average salary.

  3. 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 use np.random.default_rng() and compare the speed.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏