np.array()
np.array() turns an ordinary Python list into a NumPy array.
In this page:
Syntax
import numpy as np
arr = np.array([value1, value2, value3])
matrix = np.array([[a, b], [c, d]])
np.array()
np.array() copies data from a list, tuple or nested sequence into a new ndarray and infers the dtype. Nesting the input adds dimensions. Use the dtype argument to force a type.
Note:
- np.array copies by default.
- Use np.asarray to avoid copying when the input is already an array.
Example: np.array()
import numpy as np
a = np.array([1, 2, 3])
b = np.array([[1, 2], [3, 4]])
c = np.array([1, 2, 3], dtype=float)
print(a)
print(b)
print(c)
# Output:
# [1 2 3]
# [[1 2]
# [3 4]]
# [1. 2. 3.]
Related Topics
Common Mistakes
- Forgetting the square brackets and passing separate arguments
- Passing ragged sequences
- Expecting a view instead of a copy
Chapter Summary
- np.array converts sequences to ndarrays
- Nested lists create 2-D arrays
- dtype can be forced
- It makes a copy of the data
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: