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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

10 lines
Python 3.9+
def 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

stdout
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

  1. Use a for loop with append() for more explicit code
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.