Consecutive Nth column Difference in Tuple List using Python

PythonServer Side ProgrammingProgramming

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.

raja
Published on 15-Apr-2021 13:17:03
Advertisements