In this as its elements article we will see how to find the difference between the two successive elements for each pair of elements in a given list. The list has only numbers as its elements.
With Index
Using the index of the elements along with the for loop, we can find the difference between the successive pair of elements.
Example
listA = [12,14,78,24,24] # Given list print("Given list : \n",listA) # Using Index positions res = [listA[i + 1] - listA[i] for i in range(len(listA) - 1)] # printing result print ("List with successive difference in elements : \n" ,res)
Output
Running the above code gives us the following result −
Given list : [12, 14, 78, 24, 24] List with successive difference in elements : [2, 64, -54, 0]
With Slicing
Slicing is another technique where we slice the successive pairs from the list and then apply the zip function to get the result.
Example
listA = [12,14,78,24,24] # Given list print("Given list : \n",listA) # Using list slicing res = [x - y for y, x in zip(listA[: -1], listA[1 :])] # printing result print ("List with successive difference in elements : \n" ,res)
Output
Running the above code gives us the following result −
Given list : [12, 14, 78, 24, 24] List with successive difference in elements : [2, 64, -54, 0]
With sub
The sub method from operators module can also be used through a map function. Again we apply the slicing technique two successive pairs of elements.
Example
import operator listA = [12,14,78,24,24] # Given list print("Given list : \n",listA) # Using operator.sub res = list(map(operator.sub, listA[1:], listA[:-1])) # printing result print ("List with successive difference in elements : \n" ,res)
Output
Running the above code gives us the following result −
Given list : [12, 14, 78, 24, 24] List with successive difference in elements : [2, 64, -54, 0]