Open In App

Python – Consecutive Kth column Difference in Tuple List

Last Updated : 03 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the absolute difference of it’s Kth index. This problem has application in web development domain while working with data informations. Let’s discuss certain ways in which this task can be performed.

Examples:

Input : test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)], K = 0 
Output : [4, 4, 2] 
Explanation : 5 – 1 = 4, hence 4. 

Input : test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)], K = 2 
Output : [2, 4, 5] 
Explanation : 8 – 3 = 5, hence 5. 

Method #1: Using loop

In this, for each tuple we subtract and find absolute difference of Kth column tuples with consecutive tuples in list.

Step-by-step approach :

  • Initializes a variable K to 1, which represents the index of the column we want to compare.
  • Creates an empty list res to store the absolute differences.
  • Loops through the range of indices from 0 to the second-to-last index of the list using a for loop and the range() function. This is done to avoid going out of bounds of the list.
  • Inside the loop, the program calculates the absolute difference between the Kth column of the current tuple and the Kth column of the next tuple using the abs() function, and appends the result to the res list.
  • After the loop finishes, the program prints the resultant tuple list using the print() function and str() function to convert the list to a string.
  • The program execution ends.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Consecutive Kth column Difference in Tuple List
# Using loop
 
# initializing list
test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
res = []
for idx in range(0, len(test_list) - 1):
 
    # getting difference using abs()
    res.append(abs(test_list[idx][K] - test_list[idx + 1][K]))
     
# printing result
print("Resultant tuple list : " + str(res))


Output:

The original list is : [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)] Resultant tuple list : [1, 4, 3]

Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n),

Method #2: Using zip() + list comprehension

In this, we iterate for all the element in list using list comprehension and compare elements paired using zip(). 

Python3




# Python3 code to demonstrate working of
# Consecutive Kth column Difference in Tuple List
# Using zip() + list comprehension
 
# initializing list
test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
# zip used to pair each tuple with subsequent tuple
res = [abs(x[K] - y[K]) for x, y in zip(test_list, test_list[1:])]
     
# printing result
print("Resultant tuple list : " + str(res))


Output:

The original list is : [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)] Resultant tuple list : [1, 4, 3]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), as it creates a new list of size n to store the result.

Method #3: Using numpy library .

  • Initializes a list of tuples called test_list with four tuples containing three integers each.
  • The original list is printed using the print() function and string concatenation.
  • Initializes a variable called K with the value 1.
  • Converts the list of tuples to a NumPy array using the np.array() function and assigns it to a variable called arr.
  • Use NumPy to calculate the absolute difference between consecutive elements of the Kth column of the array using the np.abs() and np.diff() functions, and assigns the result to a variable called res.
  • Prints the resulting list of differences using the list() function to convert the NumPy array to a Python list and the print() function with string concatenation.

Python3




import numpy as np
 
# initializing list
test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
# convert the tuple list to a numpy array
arr = np.array(test_list)
 
# calculate the consecutive Kth column difference using numpy
res = np.abs(np.diff(arr[:, K]))
 
# printing result
print("Resultant tuple list : " + str(list(res)))


OUTPUT:
The original list is : [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
Resultant tuple list : [1, 4, 3]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), which is the space required to store the numpy array created from the input list.

Method #4 : Using list slicing

  • Initialize an empty list “res” to store the result.
  • Initialize “K” to the required value.
  • Iterate over the range from 0 to the length of the “test_list” minus K.
  • Within the loop, use list slicing to get the Kth column from the current tuple and the next tuple, and then calculate the absolute difference between them using abs() function.
  • Append the difference to the “res” list.
  • Return the “res” list as the result.

Python3




# Python3 code to demonstrate working of
# Consecutive Kth column Difference in Tuple List
# Using list slicing
 
# initializing list
test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
# using list slicing to get Kth column difference
res = [abs(test_list[i][K] - test_list[i+1][K]) for i in range(len(test_list)-K)]
 
# printing result
print("Resultant tuple list : " + str(res))


Output

The original list is : [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
Resultant tuple list : [1, 4, 3]

Time complexity: O(n), where n is the length of the “test_list”.
Auxiliary space: O(n), where n is the length of the “test_list”.



Similar Reads

Python | Summation of Kth Column of Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the possible accumulation of its Kth index. This problem has applications in the web development domain while working with data information. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehensio
7 min read
Python - Kth Column Product in Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the product of it’s Kth index. This problem has application in web development domain while working with data informations. Let’s discuss certain ways in which this task can be performed. Method #1: Using list comprehension + loop This tas
7 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Python Program to Merge tuple list by overlapping mid tuple
Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read
Python | Remove duplicates based on Kth element tuple list
Sometimes, while working with records, we may have a problem in which we need to remove duplicates based on Kth element of a tuple in the list. This problem has application in domains that uses records as input. Let's discuss certain ways in which this problem can be solved. Method #1: Using loop This is a brute-force method to perform this particu
8 min read
Python - Concatenate Kth element in Tuple List
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data in concatenated format. Lets discuss certain ways how one can achieve solutions to this problem. Method #
8 min read
Python - Kth Index Tuple List Mean
Sometimes, while working with Python tuple, we can have a problem in which we need to compute average of any particular index of tuples in a list. This kind of problem can have application in data domain such as web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [('Gfg', 1), ('is', 5), ('best', 7)],
6 min read