The task of calculating the difference between adjacent elements in a list involves iterating through the list and computing the difference between each consecutive pair. For example, given a list a = [5, 4, 89, 12, 32, 45], the resulting difference list would be [-1, 85, -77, 20, 13],
Using numpy
NumPy provides an efficient way to compute differences between adjacent elements, especially for large datasets. Its vectorized operations allow for faster execution, as np.diff() directly computes the differences in an array without the need for explicit loops.
import numpy as np
a = [5, 4, 89, 12, 32, 45]
a = np.array(a) # converting `a` to numpy array
diff_list = np.diff(a).tolist()
print(diff_list)
Output
[-1, 85, -77, 20, 13]
Explanation: np.diff(a) computes the difference between consecutive elements in the NumPy array , which returns a NumPy array of differences and then .tolist() converts this array into a Python list for easier handling.
Table of Content
Using list comprehension
List comprehension provides a clean way to calculate the difference between adjacent elements. It’s both concise and efficient, making it a great choice for smaller datasets where readability is key.
a = [5, 4, 89, 12, 32, 45]
diff_list = [a[i + 1] - a[i] for i in range(len(a) - 1)]
print(diff_list)
Output
[-1, 85, -77, 20, 13]
Explanation: list comprehension iterates through the indices from 0 to len(a) - 2, ensuring that each element is subtracted from the next one (a[i + 1] - a[i]).
Using itertools.pairwise
itertools.pairwise simplifies the task by generating pairs of adjacent elements, making the code clean and easy to read. It’s a good option if we want an elegant solution to handle pairs directly.
from itertools import pairwise
a = [5, 4, 89, 12, 32, 45]
diff_list = [y - x for x, y in pairwise(a)]
print(diff_list)
Output
[-1, 85, -77, 20, 13]
Explanation: pairwise(a) generates consecutive element pairs from the list a and list comprehension then computes the difference between each pair (y - x), where x and y represent adjacent elements.
Using for loop
For loop with zip is a straightforward method for calculating differences. It’s easy to understand but slightly less efficient due to list slicing.
a = [5, 4, 89, 12, 32, 45]
diff_list = [] # difference list
for x, y in zip(a[:-1], a[1:]):
diff_list.append(y - x)
print(diff_list)
Output
[-1, 85, -77, 20, 13]
Explanation: loop iterates through consecutive element pairs in a using zip(a[:-1], a[1:]), which creates tuples of adjacent elements. For each pair (x, y), it calculates y - x (the difference between consecutive elements) and appends the result to diff_list.