NumPy Array Creation
Creating arrays from Python objects
Section titled “Creating arrays from Python objects”From a list
Section titled “From a list”import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)
print(type(arr))From a nested list (2D)
Section titled “From a nested list (2D)”matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(matrix)
print(matrix.shape) # (2, 3)From a tuple
Section titled “From a tuple”arr = np.array((10, 20, 30))
print(arr)Using built-in constructors
Section titled “Using built-in constructors”np.zeros()
Section titled “np.zeros()”Create an array filled with zeros.
arr = np.zeros((2, 3))
print(arr)np.ones()
Section titled “np.ones()”arr = np.ones((3, 2))
print(arr)np.full()
Section titled “np.full()”Create an array filled with a constant value.
arr = np.full((2, 2), 7)
print(arr)np.eye() (identity matrix)
Section titled “np.eye() (identity matrix)”I = np.eye(3)
print(I)np.arange() (range with step)
Section titled “np.arange() (range with step)”Similar to Python range(), but returns a NumPy array.
arr = np.arange(0, 10, 2)
print(arr) # [0 2 4 6 8]np.linspace() (even spacing)
Section titled “np.linspace() (even spacing)”Creates num values between start and stop.
arr = np.linspace(0, 1, 5)
print(arr) # [0. 0.25 0.5 0.75 1. ]Specifying dtype during creation
Section titled “Specifying dtype during creation”arr = np.array([1, 2, 3], dtype=np.float64)
print(arr)
print(arr.dtype)Choosing the right constructor
Section titled “Choosing the right constructor” flowchart TD
A["Need an array"] --> B{"Already have data
(list/tuple)?"}
B -- "Yes" --> C["np.array(data)"]
B -- "No" --> D{"What kind of
placeholder?"}
D -- "All zeros" --> E["np.zeros(shape)"]
D -- "All ones" --> F["np.ones(shape)"]
D -- "One constant value" --> G["np.full(shape, value)"]
D -- "Identity matrix" --> H["np.eye(n)"]
D -- "Integer sequence" --> I["np.arange(start, stop, step)"]
D -- "Evenly spaced floats" --> J["np.linspace(start, stop, num)"]
Quick recap: which function to use?
Section titled “Quick recap: which function to use?”np.array(...)→ convert existing data (lists)np.zeros(shape)/np.ones(shape)→ initialize arraysnp.full(shape, value)→ constant arraysnp.eye(n)→ identity matrixnp.arange(start, stop, step)→ integer sequencesnp.linspace(start, stop, num)→ precise evenly spaced floats
Continue to: NumPy Data Types (dtypes) to learn how dtypes affect memory, performance, and numeric precision.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Zeros, Ones, and Full
Section titled “Exercise 1 – Zeros, Ones, and Full”Exercise 2 – arange vs linspace
Section titled “Exercise 2 – arange vs linspace”Exercise 3 – Identity Matrix
Section titled “Exercise 3 – Identity Matrix”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading