There are two main reasons why we would use NumPy array instead of lists in Python. These reasons are:
Now we’ll look at the proof for what I have stated above.
In the code snippets below we will see the memory usage for lists and NumPy array.
import syslist_array = [i for i in range(100)]print("Length of List array: ",len(list_array))print("Type of array: ",type(list_array))print("Memory consumption by an element in the array: ",sys.getsizeof(list_array[0]))print("Memory usage by list array: ",(sys.getsizeof(list_array[0]))*len(list_array))
Explanation:
sys
package to get the size of our array later in the code.list_array
that contains 100 elements.list_array
.Now, let’s see the NumPy array’s memory usage.
import numpy as npnumpy_array = np.arange(100)print("Length of NumPy array: ",len(numpy_array))print("Type of array: ",type(numpy_array))print("Memory consumption by an element in the array: ",numpy_array.itemsize)print("Memory usage by list array: ",numpy_array.itemsize*numpy_array.size)
Explanation
numpy
package to create an array.numpy_array
that contains 100 elements.numpy_array
.So, we can conclude that the first reason why we need NumPy arrays is because its memory consumption is far less than that of List arrays.
Now, let’s take at look at the execution time difference in the case of List arrays and NumPy arrays.
import timeimport numpy as nplist_array1 = [i for i in range(1000000)]list_array2 = [i for i in range(1000000)]start_time = time.time()list_multiply = [list_array1[i] * list_array2[i]for i in range(1000000)]final_time = time.time()print("Time taken by Lists to perform multiplication: ",(round((final_time - start_time), 2)), "millisecond")numpy_array1 = np.arange(1000000)numpy_array2 = np.arange(1000000)start_time = time.time()numpy_multiply = numpy_array1 * numpy_array2final_time = time.time()print("Time taken by Lists to perform multiplication: ",(round((final_time - start_time), 2)), "millisecond")
Explanation
From lines 4 to 13, we created two List arrays and then performed multiplication between those two arrays. Then, we calculated the execution time.
Similarly from lines 15 to 23, we created two NumPy arrays and performed multiplication between them. Then, we calculated the execution time.
So, we can conclude that the second reason why we need NumPy arrays is because it took less time to complete its execution than the List arrays.