We convert between NumPy arrays and Python lists to use the best features of both. Lists are easy to use and flexible, while arrays are fast for math.
Converting to and from Python lists in NumPy
import numpy as np # Convert Python list to NumPy array python_list = [1, 2, 3] numpy_array = np.array(python_list) # Convert NumPy array to Python list converted_list = numpy_array.tolist()
Use np.array() to convert a Python list to a NumPy array.
Use array.tolist() to convert a NumPy array back to a Python list.
import numpy as np # Empty list to array empty_list = [] empty_array = np.array(empty_list) print(empty_array) # Array to list when array has one element single_element_array = np.array([42]) single_element_list = single_element_array.tolist() print(single_element_list)
import numpy as np # List with nested lists to 2D array nested_list = [[1, 2], [3, 4]] array_2d = np.array(nested_list) print(array_2d) # Convert 2D array back to nested list list_2d = array_2d.tolist() print(list_2d)
import numpy as np # List with mixed types mixed_list = [1, 2.5, '3'] mixed_array = np.array(mixed_list) print(mixed_array) # Convert back to list back_to_list = mixed_array.tolist() print(back_to_list)
This program shows how to convert a Python list to a NumPy array, do a math operation, and convert back to a list.
import numpy as np # Create a Python list original_list = [10, 20, 30, 40] print('Original Python list:', original_list) # Convert list to NumPy array array_from_list = np.array(original_list) print('Converted to NumPy array:', array_from_list) # Perform a simple operation on the array array_from_list = array_from_list * 2 print('Array after multiplication by 2:', array_from_list) # Convert the array back to a Python list list_from_array = array_from_list.tolist() print('Converted back to Python list:', list_from_array)
Converting a list to a NumPy array is fast and allows vectorized math operations.
Converting back to a list is useful when you need Python-native data structures.
Be careful with mixed data types in lists; NumPy will convert them to a common type, often strings.
Time complexity for conversion is O(n), where n is the number of elements.
Space complexity is O(n) because a new object is created during conversion.
Use arrays when doing math, lists when you need flexibility or compatibility with Python functions.
Use np.array() to convert Python lists to NumPy arrays for fast math.
Use array.tolist() to convert NumPy arrays back to Python lists for flexibility.
Conversions are simple but watch out for data types and empty or nested lists.