Pairwise Adjacent Differences in a Python List
Computes the absolute differences between each pair of adjacent elements in a list using a concise list comprehension.
Python code
10 linesdef adjacent_differences(nums):
"""Return list of absolute differences between adjacent elements."""
return [abs(nums[i] - nums[i + 1]) for i in range(len(nums) - 1)]
if __name__ == "__main__":
sample = [3, 7, 2, 9, 5]
diffs = adjacent_differences(sample)
print("Original list:", sample)
print("Adjacent differences:", diffs)
Output
Original list: [3, 7, 2, 9, 5]
Adjacent differences: [4, 5, 7, 4]
How it works
The function uses a list comprehension that iterates over indices from 0 to len(nums)-2. For each index i, it calculates the absolute difference between nums[i] and nums[i+1] using the built-in abs() function. This produces a new list containing len(nums)-1 elements, one for each adjacent pair. The comprehension is efficient and readable, avoiding explicit loop and append calls. The main block demonstrates the function on a sample list and prints both the original and the computed differences.
Common mistakes
- Off-by-one error: iterating up to len(nums) instead of len(nums)-1 causing IndexError
- Forgetting to use abs() when negative differences are expected
- Assuming the input list is never empty; empty list returns [] without error
Variations
- Use a for loop with append() for more explicit code
- Use zip(nums, nums[1:]) to pair elements without indexing
Real-world use cases
- Computing velocity or change rates from consecutive sensor readings in IoT applications.
- Detecting abrupt changes in time-series data by comparing values across adjacent timestamps.
- Calculating gradient approximations in numerical analysis or data smoothing pipelines.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.