Python | Group tuples in list with same first value
Last Updated :
12 Apr, 2023
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
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()]
Input = [( 'x' , 'y' ), ( 'x' , 'z' ), ( 'w' , 't' )]
Output = (find( Input ))
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
from collections import defaultdict
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 = [( 'p' , 'q' ), ( 'p' , 'r' ),
( 'p' , 's' ), ( 'm' , 't' )]
Output = find( Input )
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
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)
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):
sorted_list = sorted (input_list, key = lambda x: x[ 0 ])
grouped_list = [ list (group) for key, group in itertools.groupby(sorted_list, lambda x: x[ 0 ])]
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)
|
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
Input = [( 'x' , 'y' ), ( 'x' , 'z' ), ( 'w' , 't' )]
Output = find( Input )
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):
sorted_list = sorted (input_list, key = lambda x: x[ 0 ])
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, {})
return [(k, * v) for k, v in grouped_dict.items()]
Input = [( 'x' , 'y' ), ( 'x' , 'z' ), ( 'w' , 't' )]
Output = find( Input )
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(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).
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