
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 given list using Python
Difference Between Adjacent List Elements
The given task is to calculate the difference between the adjacent elements in the given list using Python, i.e, we need to subtract the current element from the next element and repeat this for each element in the list (except the last one).
Scenario
Following is an example scenario:
Input: [10, 15, 12, 18] Output: [5, -3, 6] Explanation: Difference between 15 and 10: 15 - 10 = 5 Difference between 12 and 15: 12 - 15 = -3 Difference between 18 and 12: 18 - 12 = 6
Using List Comprehension
The Python list comprehension offers a simple way to create a list using a single line of code. It performs an operation on all the lements of an iterable and returns the resultant elements in the form of a list.
To calculate the difference between adjacent elements, we just need to specify x[i+1] - x[i] as our operation and the List object as iterable, as shown below:
[x[i+1]-x[i] for i in List]
Example 1
In the following example, we are finding the difference between the adjacent elements in the list using list comprehension:
x = [10,15,12,18] result = [x[i+1] - x[i] for i in range(len(x) - 1)] print(result)
Following is the output of the above program:
[5, -3, 6]
Example 2
In this example, we are going to calculate the adjacent difference in a list with a single element. Here, the range becomes range(0), so the list comprehension does not produce any result and returns an empty list:
x = [10] result = [x[i+1] - x[i] for i in range(len(x) - 1)] print(result)
Following is the output of the above program:
[]
Using a for loop
We can also iterate the elements of a list using loops and range() function, and subtract each element from the next one using the index values. At each step we need to append the result to the new list using the append() method.
Example
Consider the following example, where we are going to find the difference between the adjacent elements in the list [11,2,33,4,55]:
x = [11,2,33,4,55] result = [] for i in range(len(x) - 1): a = x[i+1] - x[i] result.append(a) print(result)
If we run the above program, it will generate the following output:
[-9, 31, -29, 51]
Conclusion
Finding the difference between adjacent elements in a list is a technique used to track data changes or analyze the trend. using the programming constructors like list comprehension, range() with append() makes the code short and readable.