Method # 1: Using zip()
# Python code for demo # calculate the difference # between adjacent elements in the list # initializing _list ini_list = [ 5 , 4 , 89 , 12 , 32 , 45 ] < br /> # print iniial_list print ( "intial_list" , str (ini_list)) # Difference calculation diff_list = [] for x, y in zip (ini_list [ 0 ::], ini_list [ 1 ::]): diff_list.append (y - x) # print a list of differences print ( " difference list: " , str (diff_list)) |
Exit :
intial_list [5, 4, 89, 12, 32, 45] difference list: [-1, 85, -77, 20, 13]
Method # 2: Taking a Naive Approach
# Python code for demo # calculate the difference # between adjacent elements in the list # initializing _list ini_list = [ 5 , 4 , 89 , 12 , 32 , 45 ] # print iniial_list print ( "intial_list" , str (ini_list)) # Difference calculation diff_list = [] fo r i in range ( 1 , len (ini_list)): diff_list.append (ini_list [i] - ini_list [i - 1 ]) # print a list of differences print ( " difference list: " , str (diff_list)) |
Exit:
intial_list [5, 4, 89, 12, 32, 45] difference list: [-1, 85, -77, 20, 13]
Method # 3: Using NumPy
# Python code for demo # calculate the difference # between adjacent elements in the list import numpy as np # initializing _list ini_list = np .array ([ 5 , 4 , 89 , 12 , 32 , 45 ]) # print iniial_list print ( "intial_list" , str (ini_list)) # Difference calculation diff_list = np. diff (ini_list) # print a list of differences print ( "difference list:" , str (diff_list)) | tr>
Exit :
intial_list [5 4 89 12 32 45] difference list: [-1 85 - 77 20 13]