To convert a Python list into a NumPy array, you can use the numpy.array()
function. Here’s an example:
Example:
import numpy as np
# Python list
python_list = [1, 2, 3, 4, 5]
# Convert to NumPy array
numpy_array = np.array(python_list)
print(numpy_array)
Output:
[1 2 3 4 5]
This converts a one-dimensional Python list to a NumPy array. You can similarly convert multi-dimensional lists (like a list of lists) to multi-dimensional NumPy arrays.
For example:
python_list_2d = [[1, 2], [3, 4], [5, 6]]
# Convert to 2D NumPy array
numpy_array_2d = np.array(python_list_2d)
print(numpy_array_2d)
Output:
[[1 2]
[3 4]
[5 6]]
Is there anything else you’d like to explore?