Consecutive Nth column Difference in Tuple List using Python



When it is required to find the consecutive column difference in a list of tuple, it can be iterated over, and the β€˜abs’ method and the β€˜append’ method can be used.

The β€˜abs’ method returns the absolute or positive value, and the append adds elements to a list.

Below is a demonstration of the same βˆ’

Example

 Live Demo

my_list = [(67, 89, 32), (11, 23, 44), (65, 75, 88)]

print("The list is : ")
print(my_list)

print("The value of k has been initialized")
K = 1

my_result = []
for idx in range(0, len(my_list) - 1):
   my_result.append(abs(my_list[idx][K] - my_list[idx + 1][K]))

print("The resultant list of tuple is : ")
print(my_result)

Output

The list is :
[(67, 89, 32), (11, 23, 44), (65, 75, 88)]
The value of k has been initialized
The resultant list of tuple is :
[66, 52]

Explanation

  • A list of tuple is defined, and is displayed on the console.

  • The value of K is initialized and displayed on the console.

  • An empty list is defined.

  • The list of tuple is iterated over, and the difference between the elements is determined.

  • This difference is added to the empty list.

  • This is displayed as output on the console.

Updated on: 2021-04-15T13:19:27+05:30

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements