Calculate difference between adjacent elements in given list using Python

PythonServer Side ProgrammingProgramming

In this article we will see how we create a new list from a given list by subtracting the values in the adjacent elements of the list. We have various approaches to do that.

With append and range

In this approach we iterate through list elements by subtracting the values using their index positions and appending the result of each subtraction to a new list. We use the range and len function to keep track of how many iterations to do.

Example

 Live Demo

listA= [25, 97, 13, 62, 14, 102]

print("Given list:\n",listA)
list_with_diff = []
for n in range(1, len(listA)):
   list_with_diff.append(listA[n] - listA[n-1])
print("Difference between adjacent elements in the list: \n",
   list_with_diff)

Output

Running the above code gives us the following result −

Given list:
[25, 97, 13, 62, 14, 102]
Difference between adjacent elements in the list:
[72, -84, 49, -48, 88]

With zip and list slicing

In the next approach we create a for loop to find the difference between the adjacent elements and keep appending the result to a new list.

Example

 Live Demo

listA= [25, 97, 13, 62, 14, 102]

print("Given list:\n",listA)
list_with_diff = []
for i, j in zip(listA[0::], listA[1::]):
   list_with_diff.append(j - i)
print("Difference between adjacent elements in the list: \n",
   list_with_diff)

Output

Running the above code gives us the following result −

Given list:
[25, 97, 13, 62, 14, 102]
Difference between adjacent elements in the list:
[72, -84, 49, -48, 88]
raja
Published on 10-Jul-2020 09:48:19
Advertisements