# Python | Calculate difference between adjacent elements in given list

• Last Updated : 02 Jan, 2023

Given a list, the task is to create a new list containing difference of adjacent elements in the given list. Method #1: Using zip()

## Python3

 # Python code to demonstrate# to calculate difference# between adjacent elements in list  # initialising _listini_list = [5, 4, 89, 12, 32, 45] # printing iniial_listprint("intial_list", str(ini_list)) # Calculating difference listdiff_list = []for x, y in zip(ini_list[0::], ini_list[1::]):    diff_list.append(y-x)     # printing difference listprint ("difference list: ", str(diff_list))

Output:

intial_list [5, 4, 89, 12, 32, 45]
difference list:  [-1, 85, -77, 20, 13]

Method #2: Using Naive approach

## Python3

 # Python code to demonstrate# to calculate difference# between adjacent elements in list  # initialising _listini_list = [5, 4, 89, 12, 32, 45] # printing iniial_listprint("intial_list", str(ini_list)) # Calculating difference listdiff_list = [] for i in range(1, len(ini_list)):    diff_list.append(ini_list[i] - ini_list[i-1]) # printing difference listprint ("difference list: ", str(diff_list))

Output:

intial_list [5, 4, 89, 12, 32, 45]
difference list:  [-1, 85, -77, 20, 13]

Method #3: Using numpy

## Python3

 # Python code to demonstrate# to calculate difference# between adjacent elements in list import numpy as np# initialising _listini_list = np.array([5, 4, 89, 12, 32, 45]) # printing iniial_listprint("intial_list", str(ini_list)) # Calculating difference listdiff_list = np.diff(ini_list) # printing difference listprint ("difference list: ", str(diff_list))

Output:

intial_list [ 5  4 89 12 32 45]
difference list:  [ -1  85 -77  20  13]

Method #4: Using list comprehension(one liner)

To calculate the difference between adjacent elements in a list using list comprehension, you can use the following approach:

## Python3

 # initializing the listini_list = [5, 4, 89, 12, 32, 45] # using list comprehension to calculate the difference between adjacent elementsdiff_list = [ini_list[i+1] - ini_list[i] for i in range(len(ini_list)-1)] # printing the difference listprint(diff_list)#This code is contributed by Edula Vinay Kumar Reddy

Output

[-1, 85, -77, 20, 13]

Time complexity: O(n)

Auxiliary Space: O(n)

My Personal Notes arrow_drop_up