Overview of Python Numpy

Start from the beginning
                                        

Python Numpy Arrays and List

We can implement python NumPy arrays instead of a list because of the below three reasons.

Less Memory

Fast

Convenient

Python occupies very less memory as compared to a list and is fast in execution and convenient to work with NumPy. Run the below code to check the difference in memory by using the python NumPy arrays and the list.

Example 1:

import numpy as np

import time

import sys

S = range(1000)

list1 = sys.getsizeof(5)*len(S)

print("List Memory:",list1)

D = np.arange(1000)

numpy1 = D.size*D.itemsize

print("NumPy Memory:",numpy1)

Output:

List Memory: 28000

NumPy Memory: 4000

Code Description:

To measure the memory of a list it needs the support of importing the "sys" library. The method range(1000) describes the range of 1000 numbers and is stored in the variable "S". To calculate the memory of a list of this range of 1000 values of a length of variable "S" must be multiplied with the size of an object having the element "5" in sys.getsizeof(5) method returns the memory size as 24. The "len(S)" performs calculating the number of 1000 elements and is stored in the variable "list1". The computes the memory of the list as 28000. In the next steps, we use "np.arange(1000)", while using lists we use the "range()" method and for using NumPy arrays we use the similar method "arange()" for it. The range of 1000 values is stored in the variable "D". The "D.size" performs the size of memory equivalent to "sys.getsizeof()" of lists and "D.itemsize" performs calculating the length equivalent to "len()" used for lists and the result of the multiplication returns the memory of NumPy as 4000.

The above example explains that the memory allocated in using a list is 28000 whereas the memory allocated in using a NumPy array is 4000. This major difference clearly says that NumPy arrays are preferable than using a list.

Now let us see another example which explains how using NumPy arrays is fast when compared to a list.

Example 2:

import numpy as np

import time

import sys

SIZE = 1000000

L1 = range(SIZE)

L2 = range(SIZE)

A1 = np.arange(SIZE)

A2 = np.arange(SIZE)

start = time.time()

result = [(x,y) for x,y in zip(L1,L2)]

print("List Time:",(time.time()-start)*1000)

start = time.time()

result = A1+A2

print("Numpy Time:",(time.time()-start)*1000)

Output:

List Time: 143.6159610748291

Numpy Time: 59.84044075012207

Code Description:

The zip function iterates through multiple iterations and aggregates them. To understand the zip functionality understand the below simple code.

Overview of Python NumPyWhere stories live. Discover now