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 | Group tuple into list based on value
Next article icon

Python | Group tuples in list with same first value

Last Updated : 12 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a list of tuples, the task is to print another list containing tuple of same first element. Below are some ways to achieve above tasks. 

Example: 

Input : [('x', 'y'), ('x', 'z'), ('w', 't')] Output: [('w', 't'), ('x', 'y', 'z')]

Method #1: Using extend 

Python3




# Python code to find common
# first element in list of tuple
 
# Function to solve the task
 
 
def find(Input):
    out = {}
    for elem in Input:
        try:
            out[elem[0]].extend(elem[1:])
        except KeyError:
            out[elem[0]] = list(elem)
    return [tuple(values) for values in out.values()]
 
 
# List initialization
Input = [('x', 'y'), ('x', 'z'), ('w', 't')]
 
# Calling function
Output = (find(Input))
 
# Printing
print("Initial list of tuple is :", Input)
print("List showing common first element", Output)
 
 
Output:
Initial list of tuple is : [('x', 'y'), ('x', 'z'), ('w', 't')] List showing common first element [('w', 't'), ('x', 'y', 'z')]

Time Complexity: O(n), where n is the number of tuples in the input list.
Auxiliary Space: O(n), as the output dictionary requires a space of O(n) to store the elements.

Method #2: Using defaultdict 

Python3




# Python code to find common first
# element in list of tuple
 
# Importing
from collections import defaultdict
 
# Function to solve the task
 
 
def find(pairs):
    mapp = defaultdict(list)
    for x, y in pairs:
        mapp[x].append(y)
    return [(x, *y) for x, y in mapp.items()]
 
 
# Input list initialization
Input = [('p', 'q'), ('p', 'r'),
         ('p', 's'), ('m', 't')]
 
# calling function
Output = find(Input)
 
# Printing
print("Initial list of tuple is :", Input)
print("List showing common first element", Output)
 
 
Output:
Initial list of tuple is : [('p', 'q'), ('p', 'r'), ('p', 's'), ('m', 't')] List showing common first element [('m', 't'), ('p', 'q', 'r', 's')]

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

Method #3: Using for loop

Python3




# Python code to find common
# first element in list of tuple
 
# List initialization
Input = [('x', 'y'), ('x', 'z'), ('w', 't')]
 
Output = []
v = []
for i in Input:
    if i[0] not in v:
        v.append(i[0])
for i in v:
    p = []
    p.append(i)
    for j in Input:
        if j[0] == i:
            p.append(j[1])
    p = tuple(p)
    Output.append(p)
 
# Printing
print("Initial list of tuple is :", Input)
print("List showing common first element", Output)
 
 
Output
Initial list of tuple is : [('x', 'y'), ('x', 'z'), ('w', 't')] List showing common first element [('x', 'y', 'z'), ('w', 't')]

Time complexity: O(n^2) where n is the length of Input list. The nested loop iterates over the Input list.
Auxiliary space: O(n) where n is the length of Input list. 

Method #4: Using groupby

The function find takes in a list of tuples as input and returns a new list of tuples where each tuple contains the first element of each tuple in the input list and all the second elements with the same first element.

First, the input list is sorted by the first element of each tuple using the sorted function and a lambda function as the key. This is done to ensure that all tuples with the same first element are together.

Then, the itertools.groupby function is used to group the tuples in the sorted list by the first element. The groupby function returns an iterator that returns the key and a group of tuples with the same key. The returned iterator is passed to the list function to create a list of lists, where each inner list contains the tuples with the same first element.

Finally, a list comprehension is used to create a new list of tuples, where the first element is the key and the rest are the values. The key is taken from the first tuple in each inner list, and the values are taken from the second element of each tuple in the inner list. The resulting list of tuples is returned by the function.

Python3




import itertools
 
def find(input_list):
  # Sort the input list by the first element of each tuple
  sorted_list = sorted(input_list, key=lambda x: x[0])
  # Group the tuples by the first element using itertools.groupby
  grouped_list = [list(group) for key, group in itertools.groupby(sorted_list, lambda x: x[0])]
  # Create a new list of tuples, where the first element is the key and the rest are the values
  return [tuple([group[0][0]] + [item[1] for item in group]) for group in grouped_list]
 
Input = [('x', 'y'), ('x', 'z'), ('w', 't')]
Output = find(Input)
print(Output)
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
[('w', 't'), ('x', 'y', 'z')]

Time complexity: O(n * log(n)) due to the sorting step
Auxiliary Space: O(n) to store the sorted list and grouped list

Method #5: Using set intersection and list comprehension

Use set intersection to find the common first element in the list of tuples.

Step-by-step approach:

  • Create a set of the first elements of each tuple using a list comprehension and set() function.
  • Create a list of tuples by iterating through the set and for each first element, create a list of tuples containing that element and any other elements from the original list of tuples that have the same first element.
  • Return the list of tuples containing the common first element and any other elements.

Below is the implementation of the above approach:

Python3




def find(Input):
    first_elems = set([t[0] for t in Input])
    common_elems = []
    for elem in first_elems:
        sub_list = [t for t in Input if t[0] == elem]
        common_elem = tuple([elem] + [x for t in sub_list for x in t[1:]])
        common_elems.append(common_elem)
    return common_elems
 
# List initialization
Input = [('x', 'y'), ('x', 'z'), ('w', 't')]
 
# Calling function
Output = find(Input)
 
# Printing
print("Initial list of tuple is :", Input)
print("List showing common first element", Output)
 
 
Output
Initial list of tuple is : [('x', 'y'), ('x', 'z'), ('w', 't')] List showing common first element [('w', 't'), ('x', 'y', 'z')]

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

Method #6: Using reduce():

Algorithm:

Sort the input list by the first element of each tuple.
Group the tuples by the first element using reduce() and a dictionary.
Convert the dictionary to a list of tuples.

Python3




from functools import reduce
 
def find(input_list):
    # Sort the input list by the first element of each tuple
    sorted_list = sorted(input_list, key=lambda x: x[0])
    # Group the tuples by the first element using reduce() and a dictionary
    grouped_dict = reduce(lambda x, y: x.update({y[0]: x[y[0]] + [y[1]]}) or x if y[0] in x else x.update({y[0]: [y[1]]}) or x, sorted_list, {})
    # Convert the dictionary to a list of tuples
    return [(k, *v) for k, v in grouped_dict.items()]
 
Input = [('x', 'y'), ('x', 'z'), ('w', 't')]
Output = find(Input)
# Printing
print("Initial list of tuple is :", Input)
print("List showing common first element", Output)
#This code is contributed by Rayudu.
 
 
Output
Initial list of tuple is : [('x', 'y'), ('x', 'z'), ('w', 't')] List showing common first element [('w', 't'), ('x', 'y', 'z')]

Time complexity: O(nlogn) for sorting the input list + O(n) for reducing the list to a dictionary + O(n) for converting the dictionary to a list of tuples, where n is the length of the input list. Therefore, the overall time complexity is O(nlogn).

Auxiliary Space: O(n) for the dictionary created in the reduce() function and O(n) for the list of tuples created in the return statement. Therefore, the overall space complexity is O(n).



Next Article
Python | Group tuple into list based on value
author
everythingispossible
Improve
Article Tags :
  • Python
  • Python Programs
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Python | Group tuple into list based on value
    Sometimes, while working with Python tuples, we can have a problem in which we need to group tuple elements to nested list on basis of values allotted to it. This can be useful in many grouping applications. Let's discuss certain ways in which this task can be performed. Method #1 : Using itemgetter
    6 min read
  • Python Group by matching second tuple value in list of tuples
    Given a list of tuples, the task is to group the tuples by matching the second element in the tuples. We can achieve this using dictionary by checking the second element in each tuple. Examples: Input : [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)] Output: {80: [(20, 80), (31, 80)], 11: [(88, 11
    3 min read
  • Python | Get first index values in tuple of strings
    Yet another peculiar problem which might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This articles solves problem of extracting only the fi
    5 min read
  • Python - Group single item dictionaries into List values
    Given a List of single-item dictionaries, group them into dictionary value lists according to similar values. Input : [{"Gfg" : 3}, {"is": 8}, {"Gfg": 18}, {"Best": 33}]Output : {'Gfg': [3, 18], 'is': [8], 'Best': [33]} Explanation : Each key converted to list values and dictionary. Input : [{"Gfg"
    6 min read
  • Removing Tuples from a List by First Element Value - Python
    In this problem we need to delete tuples based on a specific condition related to their first element. For example: We are given the list data = [("GeeksforGeeks", "Python", 1000), ("CodingForAll", "Java", 1200)] and we need to remove all tuples where the first element is "GeeksforGeeks", the desire
    3 min read
  • Python - Convert tuple list to dictionary with key from a given start value
    Given a tuple list, the following article focuses on how to convert it to a dictionary, with keys starting from a specified start value. This start value is only to give a head start, next keys will increment the value of their previous keys. Input : test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10,
    4 min read
  • Python - Group Similar items to Dictionary Values List
    We are given a list of items and our task is to group similar elements together as dictionary values. The keys will be the unique items and their values will be lists containing all occurrences of that item. For example, given ['apple', 'banana', 'apple', 'orange', 'banana'], the output should be: {
    2 min read
  • Python - Dictionaries with Unique Value Lists
    Given List of dictionaries with list values, extract unique dictionaries. Input : [{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}] Output : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}] Explanation : Both are similar dictionaries, and hence 1 is removed.
    4 min read
  • Python - Nested List to single value Tuple
    Sometimes, while working with Python data, we can have problems in which we need to convert Python Nested lists to single values tuples. This kind of problem can have applications in domains such as web development and competitive programming. Let's discuss certain ways in which this task can be per
    7 min read
  • Python | Split list in uneven groups
    Sometimes, while working with python, we can have a problem of splitting a list. This problem is quite common and has many variations. Having solutions to popular variations proves to be good in long run. Let's discuss certain way to split list in uneven groups as defined by other list. Method 1: Us
    6 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