Calculate difference between adjacent elements in given list using Python

Calculating the difference between adjacent elements in a list is a common task in data analysis. Python provides several efficient approaches to solve this problem using list comprehension, loops, or built-in functions.

Problem Definition

Given a list, we need to calculate the difference between each adjacent pair of elements (next element minus current element). The result will have one fewer element than the original list.

Example Scenario

Input: [10, 15, 12, 18]
Output: [5, -3, 6]

Explanation:
15 - 10 = 5
12 - 15 = -3
18 - 12 = 6

Using List Comprehension

List comprehension offers a concise way to calculate adjacent differences in a single line of code ?

numbers = [10, 15, 12, 18]
result = [numbers[i+1] - numbers[i] for i in range(len(numbers) - 1)]
print(result)
[5, -3, 6]

Edge Case: Single Element List

When the list has only one element, there are no adjacent pairs, so an empty list is returned ?

single_element = [10]
result = [single_element[i+1] - single_element[i] for i in range(len(single_element) - 1)]
print(result)
[]

Using a For Loop

The traditional loop approach provides more control and is easier to understand for beginners ?

numbers = [11, 2, 33, 4, 55]
result = []

for i in range(len(numbers) - 1):
    difference = numbers[i+1] - numbers[i]
    result.append(difference)

print(result)
[-9, 31, -29, 51]

Using NumPy diff()

For numerical computations, NumPy provides a built-in diff() function that's highly optimized ?

import numpy as np

numbers = [10, 15, 12, 18]
result = np.diff(numbers)
print(result.tolist())  # Convert back to list
[5, -3, 6]

Comparison of Methods

Method Readability Performance Best For
List Comprehension High Good Small to medium lists
For Loop Very High Good Learning and debugging
NumPy diff() High Excellent Large numerical arrays

Conclusion

List comprehension is the most Pythonic approach for calculating adjacent differences in small to medium lists. For large numerical datasets, NumPy's diff() function provides superior performance.

Updated on: 2026-03-25T09:01:25+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements