← Back to NumPy Course | Chapter 2: Creating Arrays | Lesson 1 of 7

np.array()

np.array() turns an ordinary Python list into a NumPy array.

In this page:

  1. np.array()
Syntax
python
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()

python
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
  1. Forgetting the square brackets and passing separate arguments
  2. Passing ragged sequences
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.