
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate Difference Between Adjacent Elements in List using Python
In this article we will see how we create a new list from a given list by subtracting the values in the adjacent elements of the list. We have various approaches to do that.
With append and range
In this approach we iterate through list elements by subtracting the values using their index positions and appending the result of each subtraction to a new list. We use the range and len function to keep track of how many iterations to do.
Example
listA= [25, 97, 13, 62, 14, 102] print("Given list:\n",listA) list_with_diff = [] for n in range(1, len(listA)): list_with_diff.append(listA[n] - listA[n-1]) print("Difference between adjacent elements in the list: \n", list_with_diff)
Output
Running the above code gives us the following result −
Given list: [25, 97, 13, 62, 14, 102] Difference between adjacent elements in the list: [72, -84, 49, -48, 88]
With zip and list slicing
In the next approach we create a for loop to find the difference between the adjacent elements and keep appending the result to a new list.
Example
listA= [25, 97, 13, 62, 14, 102] print("Given list:\n",listA) list_with_diff = [] for i, j in zip(listA[0::], listA[1::]): list_with_diff.append(j - i) print("Difference between adjacent elements in the list: \n", list_with_diff)
Output
Running the above code gives us the following result −
Given list: [25, 97, 13, 62, 14, 102] Difference between adjacent elements in the list: [72, -84, 49, -48, 88]
Advertisements