Numpy How to Convert List to Numpy Array
numpy.array(your_list) to convert a Python list to a numpy array, for example: np.array([1, 2, 3]).Examples
How to Think About It
Algorithm
Code
import numpy as np my_list = [1, 2, 3] my_array = np.array(my_list) print(my_array)
Dry Run
Let's trace converting the list [1, 2, 3] to a numpy array.
Input list
my_list = [1, 2, 3]
Convert to numpy array
my_array = np.array(my_list) # creates array([1, 2, 3])
Print result
print(my_array) # outputs [1 2 3]
| Step | Action | Value |
|---|---|---|
| 1 | Input list | [1, 2, 3] |
| 2 | Convert to numpy array | array([1, 2, 3]) |
| 3 | Print result | [1 2 3] |
Why This Works
Step 1: Why use numpy.array()
The numpy.array() function reads the list and creates a numpy array object that supports fast numerical operations.
Step 2: Preserves data order
The order and values in the list stay the same in the numpy array, so your data is unchanged but now in a powerful format.
Step 3: Enables numpy features
Once converted, you can use numpy's math functions, slicing, and broadcasting on the array.
Alternative Approaches
import numpy as np my_list = [1, 2, 3] my_array = np.asarray(my_list) print(my_array)
import numpy as np my_list = [1, 2, 3] my_array = np.fromiter(my_list, dtype=int) print(my_array)
Complexity: O(n) time, O(n) space
Time Complexity
Converting a list to a numpy array requires reading each element once, so it takes linear time proportional to the list size.
Space Complexity
A new numpy array is created, so space used is proportional to the number of elements in the list.
Which Approach is Fastest?
Using numpy.asarray() can be faster if the input is already an array, as it avoids copying data.
| Approach | Time | Space | Best For |
|---|---|---|---|
| numpy.array() | O(n) | O(n) | General list to array conversion |
| numpy.asarray() | O(n) or O(1) | O(n) or O(1) | Avoiding copy if input is array |
| numpy.fromiter() | O(n) | O(n) | Large iterables with known dtype |