How to Use np.array in NumPy: Syntax and Examples
Use
np.array() to create a NumPy array from a list or other sequence. Pass your data inside the parentheses, like np.array([1, 2, 3]), to get a fast, efficient array for numerical operations.Syntax
The basic syntax of np.array() is simple:
np.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
Here, object is the data you want to convert into an array, usually a list or tuple. dtype sets the data type (like int or float). Other parameters control copying and array shape but are optional.
python
np.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
Example
This example shows how to create a NumPy array from a Python list and check its type and contents.
python
import numpy as np # Create a NumPy array from a list arr = np.array([10, 20, 30, 40]) # Print the array print(arr) # Print the type to confirm it's a NumPy array print(type(arr))
Output
[10 20 30 40]
<class 'numpy.ndarray'>
Common Pitfalls
One common mistake is passing a list of lists with uneven lengths, which creates an array of dtype=object instead of a numeric array. Another is forgetting to import NumPy as np.
Also, using np.array() on a list of mixed data types can lead to unexpected data type conversions.
python
import numpy as np # Wrong: uneven nested lists arr_wrong = np.array([[1, 2], [3, 4, 5]]) print(arr_wrong) print(arr_wrong.dtype) # Right: uniform nested lists arr_right = np.array([[1, 2], [3, 4]]) print(arr_right) print(arr_right.dtype)
Output
[list([1, 2]) list([3, 4, 5])]
object
[[1 2]
[3 4]]
int64
Quick Reference
| Parameter | Description |
|---|---|
| object | Input data (list, tuple, etc.) to convert to array |
| dtype | Optional: desired data type (e.g., int, float) |
| copy | Optional: whether to copy data (default True) |
| order | Optional: memory layout ('C', 'F', or 'K') |
| subok | Optional: if True, subclasses are preserved |
| ndmin | Optional: minimum number of dimensions for output array |
Key Takeaways
Use np.array() to convert lists or tuples into fast NumPy arrays.
Ensure input data is uniform in shape and type for best results.
Remember to import NumPy as np before using np.array().
Specify dtype if you need a specific data type for the array.
Avoid uneven nested lists to prevent object arrays.