Python | Group tuples in list with same first value
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
# 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) |
chevron_right
filter_none
Output:
Initial list of tuple is : [('x', 'y'), ('x', 'z'), ('w', 't')]
List showing common first element [('w', 't'), ('x', 'y', 'z')]
Method #2: Using defaultdict
# 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) |
chevron_right
filter_none
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')]
Recommended Posts:
- Python | Group by matching second tuple value in list of tuples
- Python | Count tuples occurrence in list of tuples
- Python | Remove tuples from list of tuples if greater than n
- Python | Find the tuples containing the given element from a list of tuples
- Python | Remove tuples having duplicate first value from given list of tuples
- Python | Remove duplicate tuples from list of tuples
- Python | Combining tuples in list of tuples
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Convert list of strings to list of tuples
- Python | Convert list of tuples to list of strings
- Python | Convert list of tuples to list of list
- Python | Convert list of tuples into list
- Python | Update a list of tuples using another list
- Python | Min and Max value in list of tuples
- Python | Get unique tuples from list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



