Consecutive Nth column Difference in Tuple List using Python

When working with lists of tuples, you may need to find the consecutive differences between elements in a specific column. This can be achieved by iterating through the list and using the abs() method to calculate absolute differences.

The abs() method returns the absolute (positive) value of a number, while append() adds elements to a list.

Example

Let's find the consecutive differences in the second column (index 1) of a tuple list ?

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 is:")
print(my_result)
The list is:
[(67, 89, 32), (11, 23, 44), (65, 75, 88)]
The value of k has been initialized
The resultant list is:
[66, 52]

How It Works

The algorithm compares consecutive tuples at column index K:

  • First comparison: abs(89 - 23) = 66

  • Second comparison: abs(23 - 75) = 52

Using List Comprehension

A more concise approach using list comprehension ?

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

result = [abs(my_list[i][K] - my_list[i + 1][K]) for i in range(len(my_list) - 1)]
print("Consecutive differences:", result)
Consecutive differences: [66, 52]

Different Column Example

Finding differences in the first column (index 0) ?

my_list = [(67, 89, 32), (11, 23, 44), (65, 75, 88)]
K = 0  # First column

result = [abs(my_list[i][K] - my_list[i + 1][K]) for i in range(len(my_list) - 1)]
print("First column differences:", result)
First column differences: [56, 54]

Conclusion

Use abs() with list iteration to find consecutive column differences in tuple lists. List comprehension provides a more concise solution for the same task.

Updated on: 2026-03-25T18:55:06+05:30

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements