Converting to and from Python lists in NumPy - Time & Space Complexity
We want to understand how long it takes to convert between numpy arrays and Python lists.
How does the time grow when the data size gets bigger?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.arange(1000) # Create a numpy array with 1000 elements
py_list = arr.tolist() # Convert numpy array to Python list
new_arr = np.array(py_list) # Convert Python list back to numpy array
This code converts a numpy array to a Python list, then back to a numpy array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Traversing all elements to copy data during conversion.
- How many times: Once for each element when converting to list, and once again when converting back to array.
As the number of elements increases, the time to convert grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (10 to list + 10 to array) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: The operations roughly double the input size, growing linearly.
Time Complexity: O(n)
This means the time to convert grows directly in proportion to the number of elements.
[X] Wrong: "Conversion between numpy arrays and lists is instant regardless of size."
[OK] Correct: Each element must be copied, so bigger data takes more time.
Understanding this helps you explain data handling efficiency and choose the right data structures in real projects.
"What if we convert a nested numpy array (multi-dimensional) to a list? How would the time complexity change?"