NumPy Arrays vs. Python Lists

This code compares the time required by Python to compute the squares of the first 10,000,000 positive integers using both Python lists and NumPy arrays.

The result is impressive: during a test run with this code, NumPy was 88 times faster! This code uses the time module to record the start and end times of each of the two operations, then calculates the ratio between the two elapsed times.

import numpy as np
import time

numbers_list= [ k for k in range(10000000)]
numbers_array=np.array(numbers_list)

start_time = time.time()
numbers_list_sqrt = [k**2 for k in numbers_list]
end_time = time.time()
execution_time_list = end_time - start_time

start_time = time.time()
numbers_array_sqrt = numbers_array**2
end_time = time.time()
execution_time_array = end_time - start_time

print(execution_time_list/execution_time_array)

Why ? NumPy arrays are implemented in C, which allows for efficient memory management and execution. NumPy operations are vectorized : they operate on entire arrays rather than individual elements

see more articles