# NumPy Difference

Submitted by moazkhan on Thursday, July 16, 2020 - 14:58.

## In this tutorial you will learn:

- What is the NumPy Difference?
- Implementation of difference in Python
- Python Syntax

## NumPy Difference

Difference is just another name for the operation of subtraction. It is a very common operation in the world of computation, mathematics and science. For taking a discrete difference it is necessary that there are 2 numbers involved, they can be equal, lesser or greater to each other.## Implementation of Difference

Function diff() is used to get the difference of each element from its subsequent element in the array, the function takes in an array having size ‘s’ as a mandatory parameter and returns an array having size ‘s-1’. Suppose if we have an array with variable [a,b,c,d,e], the result of the applying the diff() function on the array will be [b-a,c-b,d-c,e-d]. You can observe that the size of input array has been decreased by 1. Lets take an example, in this example we will be giving an array having size 4 as a parameter to the diff() function, an d the diff() function will be returning the output array having size 3.- #importing the NumPy library
- import numpy as np
- #declaring an array
- my_arr= np.array([4,8,12,16])
- print('Array of which difference is being taken:', my_arr)
- #finding the difference of contents of an array
- res = np.diff(my_arr)
- #printing the result
- print('The result of diff() function:', res)

- #importing the NumPy library
- import numpy as np
- #declaring an array
- my_arr= np.array([4,45,93,118])
- print('Array of which difference is being taken:', my_arr)
- #finding the difference of contents of an array with n=1
- res = np.diff(my_arr,n=1)
- print('The result after applying diff() with n=1:',res)
- #finding the difference of contents of an array with n=2
- res = np.diff(my_arr,n=2)
- print('The result after applying diff() with n=2:',res)
- #finding the difference of contents of an array with n=3
- res = np.diff(my_arr,n=3)
- print('The result after applying diff() with n=3:',res)

## Book traversal links for NumPy Difference

## Add new comment

- 171 views