Python | Calculate difference between adjacent elements in given list
Given a list, the task is to create a new list containing difference of adjacent elements in the given list.
Method #1: Using zip()
# Python code to demonstrate # to calculate difference # between adjacent elements in list # initialising _list ini_list = [5, 4, 89, 12, 32, 45] # printing iniial_list print("intial_list", str(ini_list)) # Calculating difference list diff_list = [] for x, y in zip(ini_list[0::], ini_list[1::]): diff_list.append(y-x) # printing difference list print ("difference list: ", str(diff_list)) |
chevron_right
filter_none
Output:
intial_list [5, 4, 89, 12, 32, 45] difference list: [-1, 85, -77, 20, 13]
Method #2: Using Naive approach
# Python code to demonstrate # to calculate difference # between adjacent elements in list # initialising _list ini_list = [5, 4, 89, 12, 32, 45] # printing iniial_list print("intial_list", str(ini_list)) # Calculating difference list diff_list = [] for i in range(1, len(ini_list)): diff_list.append(ini_list[i] - ini_list[i-1]) # printing difference list print ("difference list: ", str(diff_list)) |
chevron_right
filter_none
Output:
intial_list [5, 4, 89, 12, 32, 45] difference list: [-1, 85, -77, 20, 13]
Method #3: Using numpy
# Python code to demonstrate # to calculate difference # between adjacent elements in list import numpy as np # initialising _list ini_list = np.array([5, 4, 89, 12, 32, 45]) # printing iniial_list print("intial_list", str(ini_list)) # Calculating difference list diff_list = np.diff(ini_list) # printing difference list print ("difference list: ", str(diff_list)) |
chevron_right
filter_none
Output:
intial_list [ 5 4 89 12 32 45] difference list: [ -1 85 -77 20 13]
Recommended Posts:
- Python | Joining only adjacent words in list
- Python | Maximum absolute difference list of list
- Python | Sorting list of lists with similar list elements
- Python | Replace elements in second list with index of same element in first list
- Python | Add list elements with a multi-list based on index
- Python | Indices of sorted list of list elements
- Python | Maximum sum of elements of list in a list of lists
- Python | Set Difference in list of dictionaries
- Python | Triple list difference
- Python | Generate successive element difference list
- Python program to find sum of absolute difference between all pairs in a list
- Python | Get first and last elements of a list
- Python | Get last N elements from given list
- Python | Check if all elements in a List are same
- Python | Remove last K elements of list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



