NumPy is faster and uses less memory than Python lists for numbers. It helps do math on many numbers easily.
Why NumPy over Python lists
import numpy as np # Create a NumPy array from a Python list numbers_list = [1, 2, 3, 4, 5] numbers_array = np.array(numbers_list)
NumPy arrays are created from Python lists using np.array().
NumPy arrays support fast math operations on all elements at once.
import numpy as np # Empty list to NumPy array empty_list = [] empty_array = np.array(empty_list) print(empty_array)
import numpy as np # Single element list single_element_list = [10] single_element_array = np.array(single_element_list) print(single_element_array)
import numpy as np # Multi-dimensional list multi_list = [[1, 2], [3, 4]] multi_array = np.array(multi_list) print(multi_array)
This program shows how Python lists and NumPy arrays store numbers differently. It prints their memory sizes and the time taken to add 1 to each element.
import numpy as np # Create a Python list of numbers python_list = [1, 2, 3, 4, 5] print("Python list:", python_list) # Create a NumPy array from the list numpy_array = np.array(python_list) print("NumPy array:", numpy_array) # Show memory size difference import sys list_size = sys.getsizeof(python_list) array_size = numpy_array.nbytes print(f"Memory size of Python list: {list_size} bytes") print(f"Memory size of NumPy array: {array_size} bytes") # Show speed difference for adding 1 to each element import time start_list = time.time() list_plus_one = [x + 1 for x in python_list] end_list = time.time() start_array = time.time() array_plus_one = numpy_array + 1 end_array = time.time() print(f"Time for list addition: {end_list - start_list:.6f} seconds") print(f"Time for NumPy addition: {end_array - start_array:.6f} seconds")
NumPy arrays use less memory because they store data in a compact way.
NumPy operations are faster because they run compiled code under the hood.
Common mistake: expecting NumPy arrays to behave exactly like Python lists; they have different methods and behaviors.
Use NumPy when working with large numeric data or needing fast math operations.
NumPy arrays are faster and use less memory than Python lists for numbers.
NumPy makes math on many numbers easy and efficient.
Use NumPy when working with large or multi-dimensional numeric data.