Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Concatenate consecutive elements in Tuple
Next article icon

Python – Consecutive Kth column Difference in Tuple List

Last Updated : 03 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
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”.



Next Article
Python - Concatenate consecutive elements in Tuple
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Python - Consecutive Tuple difference
    Given List of tuples, find index-wise absolute difference of consecutive tuples. Input : test_list = [(5, 3), (1, 4), (9, 5), (3, 5)] Output : [(4, 1), (7, 1), (6, 0)] Explanation : 5 - 1 = 4, 4 - 3 = 1. hence (4, 1) and so on. Input : test_list = [(9, 5), (3, 5)] Output : [(6, 0)] Explanation : 9 -
    4 min read
  • Python - Concatenate consecutive elements in Tuple
    Sometimes, while working with data, we can have a problem in which we need to find cumulative results. This can be of any type, product, or summation. Here we are gonna discuss adjacent element concatenation. Let’s discuss certain ways in which this task can be performed. Method #1 : Using zip() + g
    4 min read
  • Python - K difference Consecutive elements
    Given a list of integer elements, check for each element if its difference with successive element is K. Input : test_list = [5, 6, 3, 2, 5, 3, 4], K = 1 Output : [True, False, True, False, False, True] Explanation : 5, 6; 3, 2; and 3, 4 have 1 diff. between them. Input : test_list = [5, 6, 3, 2, 5,
    4 min read
  • Python | Arrange Tuples consecutively in list
    Sometimes, while working with tuple list, we may require a case in which we require that a tuple starts from the end of previous tuple, i.e the element 0 of every tuple should be equal to ending element of tuple in list of tuple. This type of problem and sorting is useful in competitive programming.
    3 min read
  • Python | Convert Lists to column tuples
    Sometimes, while working with data, we can have a problem in which we need to get alike index elements in a single container. This means the columns of Matrix/Multiple lists need to be converted to list of tuples, each comprising of like index elements. Let's discuss certain ways in which this task
    11 min read
  • Python - Filter consecutive elements Tuples
    Given a Tuple list, filter tuples that are made from consecutive elements, i.e diff is 1. Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 4), (6, 4, 6, 3)] Output : [(3, 4, 5, 6)] Explanation : Only 1 tuple adheres to condition. Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6,
    5 min read
  • Python - Extract Kth element of every Nth tuple in List
    Given list of tuples, extract Kth column element of every Nth tuple. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)], K = 2, N = 3 Output : [3, 8, 10] Explanation : From 0th, 3rd, and 6th tuple, 2nd elements are 3, 8, 10. Input :test_list
    8 min read
  • Python | Set Difference in list of dictionaries
    The difference of two lists have been discussed many times, but sometimes we have a large number of data and we need to find the difference i.e the elements in dict2 not in 1 to reduce the redundancies. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension The na
    3 min read
  • Difference between two Lists in Python
    The difference between two lists in Python refers to the elements that are present in one list but not in the other. For example, finding the difference between lists a = [1, 2, 3, 4] and b = [3, 4, 5, 6] can result in [1, 2] by removing the common elements (3 and 4). Using setSet operations are mos
    3 min read
  • Python | Minimum Difference in Matrix Columns
    This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the minimum difference between the like indices when compared with the next list. The minimum difference between the like elements in that index is returned. Let’s d
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences