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 | Summation of tuples in list
Next article icon

Python – Pairs with Sum equal to K in tuple list

Last Updated : 05 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with data, we can have a problem in which we need to find the sum of pairs of tuple list. And specifically the sum that is equal to K. This kind of problem can be important in web development and competitive programming. Lets discuss certain ways in which this task can be performed. 

Method #1: Using loop This can be solved using loop. This is brute way in which this task is performed. In this, we iterate the list for pair summation and retain whose sum is K. 

Python3




# Python3 code to demonstrate
# Pairs with Sum equal to K in tuple list
# using loop
 
# Initializing list
test_list = [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing K
K = 9
 
# Pairs with Sum equal to K in tuple list
# using loop
res = []
for ele in test_list:
    if ele[0] + ele[1] == K:
        res.append(ele)
 
# printing result
print ("List after extracting pairs equal to K : " + str(res))
 
 
Output : 
The original list is : [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)] List after extracting pairs equal to K : [(4, 5), (3, 6), (1, 8)]

Time Complexity: O(n) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.

Method #2: Using list comprehension This is yet another way in which this task can be performed. In this, we extract the elements in similar method as above, the difference is that we perform this task as shorthand and in one line. 

Python3




# Python3 code to demonstrate
# Pairs with Sum equal to K in tuple list
# using list comprehension
 
# Initializing list
test_list = [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing K
K = 9
 
# Pairs with Sum equal to K in tuple list
# using list comprehension
res = [(ele[0], ele[1]) for ele in test_list if ele[0] + ele[1] == K]
 
# printing result
print ("List after extracting pairs equal to K : " + str(res))
 
 
Output : 
The original list is : [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)] List after extracting pairs equal to K : [(4, 5), (3, 6), (1, 8)]

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method #3 : Using sum() and list() methods

Python3




# Python3 code to demonstrate
# Pairs with Sum equal to K in tuple list
# using loop
 
# Initializing list
test_list = [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing K
K = 9
 
# Pairs with Sum equal to K in tuple list
# using loop
res = []
for ele in test_list:
    if sum(list(ele)) == K:
        res.append(ele)
 
# printing result
print ("List after extracting pairs equal to K : " + str(res))
 
 
Output
The original list is : [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)] List after extracting pairs equal to K : [(4, 5), (3, 6), (1, 8)]

Method #4 : Using lamda and filter() methods

Python3




# Python3 code to demonstrate
# Pairs with Sum equal to K in tuple list
# using loop
  
# Initializing list
test_list = [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing K
K = 9
  
# Pairs with Sum equal to K in tuple list
# using loop
res = list(filter(lambda x: x[0] + x[1] == K, test_list))
 
# printing result
print ("List after extracting pairs equal to K : " + str(res))
 
 
Output
The original list is : [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)] List after extracting pairs equal to K : [(4, 5), (3, 6), (1, 8)]

Time complexity: O(n)

Auxiliary Space: O(n)

Method 5 : Using a dictionary. 

step-by-step approach:

Initialize an empty dictionary dict_pairs.
Loop through each tuple t in the input list test_list.
Calculate the difference diff between the target sum K and the first element of the tuple t[0].
If diff is already a key in the dictionary, append the current tuple t to the list of tuples mapped to that key.
If diff is not already a key in the dictionary, add it as a key with a value of a list containing the current tuple t.
Return the values of the dictionary as the final result.

Python3




# Python3 code to demonstrate
# Pairs with Sum equal to K in tuple list
# using dictionary
 
# Initializing list
test_list = [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]
 
# Initializing K
K = 9
 
# Initializing empty dictionary
dict_pairs = {}
 
# Initializing empty result list
res = []
 
# Loop through each tuple in the input list
for t in test_list:
    # Calculate the sum of the tuple
    s = sum(t)
    # If the sum is equal to K, add the tuple to the result list
    if s == K:
        res.append(t)
    # If the sum is not equal to K, add the tuple to the dictionary
    else:
        if s not in dict_pairs:
            dict_pairs[s] = []
        dict_pairs[s].append(t)
 
# Find pairs with sum equal to K in the dictionary
for key in dict_pairs:
    if K - key in dict_pairs:
        res.extend([(x, y) for x in dict_pairs[key] for y in dict_pairs[K - key]])
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Printing result
print ("List after extracting pairs equal to K : " + str(res))
 
 
Output
The original list is : [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)] List after extracting pairs equal to K : [(4, 5), (3, 6), (1, 8)]

Time complexity: O(n), where n is the number of tuples in the input list.
Auxiliary space: O(n), to store the dictionary of pairs.



Next Article
Python | Summation of tuples in list
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Total equal pairs in List
    Given a list, the task is to write a python program to compute total equal digit pairs, i.e extract the number of all elements with can be dual paired with similar elements present in the list. Input : test_list = [2, 4, 5, 2, 5, 4, 2, 4, 5, 7, 7, 8, 3] Output : 4 Explanation : 4, 2 and 5 have 3 occ
    7 min read
  • Python - Split list into all possible tuple pairs
    Given a list, the task is to write a python program that can split it into all possible tuple pairs combinations. Input : test_list = [4, 7, 5, 1, 9] Output : [[4, 7, 5, 1, 9], [4, 7, 5, (1, 9)], [4, 7, (5, 1), 9], [4, 7, (5, 9), 1], [4, (7, 5), 1, 9], [4, (7, 5), (1, 9)], [4, (7, 1), 5, 9], [4, (7,
    3 min read
  • Python | Summation of tuples in list
    Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have applications in cases in which we deal with a lot of record data. Let's discuss certain ways in which this problem can be solved. Metho
    7 min read
  • Python | Find all triplets in a list with given sum
    Given a list of integers, write a Python program to find all triplets that sum up to given integer 'k'. Examples: Input : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 10 Output : [(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)] Input : [12, 3, 6, 1, 6, 9], k = 24 Output : [(12, 6, 6), (12, 9, 3)] Approach #1 :
    4 min read
  • Python | Unique pairs in list
    Sometimes, while working with python list, we can have a binary matrix ( Nested list having 2 elements ). And we can have a problem in which we need to find the uniqueness of a pair. A pair is unique irrespective of order, it doesn't appear again in list. Let's discuss certain way in which this task
    6 min read
  • Python - Filter tuple with all same elements
    Given List of tuples, filter tuples that have same values. Input : test_list = [(5, 6, 5, 5), (6, 6, 6), (9, 10)] Output : [(6, 6, 6)] Explanation : 1 tuple with same elements. Input : test_list = [(5, 6, 5, 5), (6, 5, 6), (9, 10)] Output : [] Explanation : No tuple with same elements. Method #1 : U
    4 min read
  • Python - Closest Sum Pair in List
    Sometimes, we desire to get the elements that sum to a particular element. But in cases we are not able to find that, our aim changes to be one to find the closest one. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using diction
    4 min read
  • Python | Pair and combine nested list to tuple list
    Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the
    10 min read
  • Python - Cross Pairing in Tuple List
    Given 2 tuples, perform cross pairing of corresponding tuples, convert to single tuple if 1st element of both tuple matches. Input : test_list1 = [(1, 7), (6, 7), (8, 100), (4, 21)], test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)] Output : [(7, 3)] Explanation : 1 occurs as tuple element at pos. 1 in
    5 min read
  • 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 ca
    7 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