Open In App

Python | Group tuple into list based on value

Improve
Improve
Like Article
Like
Save
Share
Report

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() + list comprehension + groupby() 

The combination of above functions can be used to perform this task. In this, we access the value using itemgetter() and logic for grouping is performed using groupby() and list comprehension. 

Python3




# Python3 code to demonstrate working of
# Group tuple into list based on value
# using itemgetter() + list comprehension + groupby()
from operator import itemgetter
from itertools import groupby
 
# initialize list
test_list = [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Group tuple into list based on value
# using itemgetter() + list comprehension + groupby()
res = [[i for i, j in temp]\
    for key, temp in groupby(test_list, key = itemgetter(1))]
 
# printing result
print("The list after grouping by value : " + str(res))


Output

The original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
The list after grouping by value : [[1, 2], [6], [5, 6, 8]]

Time Complexity: O(n*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 #2: Using map() + itemgetter() + groupby() + list comprehension

This method is similar to the above method, the only difference is that we chose a map for the formation of keys as nested list for formation of new resultant lists. 

Python3




# Python3 code to demonstrate working of
# Group tuple into list based on value
# using map() + itemgetter() + groupby() + list comprehension
from operator import itemgetter
from itertools import groupby
 
# initialize list
test_list = [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Group tuple into list based on value
# using map() + itemgetter() + groupby() + list comprehension
res = [list(map(itemgetter(0), temp))
    for (key, temp) in groupby(test_list, itemgetter(1))]
 
# printing result
print("The list after grouping by value : " + str(res))


Output

The original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
The list after grouping by value : [[1, 2], [6], [5, 6, 8]]

The time complexity of this approach is O(n log n) due to sorting by the itemgetter() function. The groupby() function and the list comprehension run in linear time.

The auxiliary space complexity is O(n) for the list used to store the grouped tuples, where n is the length of the input list.

Method #3 : Using defaultdict()

This method uses the defaultdict() from the collections module to group the tuples based on the second element of the tuple as the key and the first element as the value. The result is then transformed into a list of lists using list comprehension.

Python3




# Python3 code to demonstrate working of
# Group tuple into list based on value
# using defaultdict() + list comprehension
from collections import defaultdict
 
# initialize list
test_list = [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Group tuple into list based on value
# using defaultdict() + list comprehension
temp = defaultdict(list)
for i, j in test_list:
    temp[j].append(i)
res = [temp[i] for i in temp]
 
# printing result
print("The list after grouping by value : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy


Output

The original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
The list after grouping by value : [[1, 2], [6], [5, 6, 8]]

Time complexity: O(n)
Auxiliary Space : O(n)

Method 4:  using the itertools module’s groupby() function:

Approach:

  1. Import the itertools module.
  2. Initialize the list with tuples.
  3. Sort the list based on the second element of each tuple using the sorted() function with a lambda function as the key.
  4. Use the groupby() function from the itertools module to group the sorted list based on the second element of each tuple. We also use a lambda function to get the second element as the key.
  5. Iterate through each group and append the first element of each tuple to a list.
  6. Print the result.

Python3




# import itertools module
import itertools
 
# initialize list
test_list = [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Group tuple into list based on value
# using itertools.groupby() function
temp = itertools.groupby(
    sorted(test_list, key=lambda x: x[1]), key=lambda x: x[1])
res = [[i[0] for i in g] for k, g in temp]
 
# printing result
print("The list after grouping by value : " + str(res))


Output

The original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
The list after grouping by value : [[5, 6, 8], [1, 2], [6]]

Time complexity: O(nlogn), where n is the number of tuples in the list. We need to sort the list before using the groupby() function.
Auxiliary space: O(n), where n is the number of tuples in the list. We need to store the values in a list.

Method #5: Using dictionary and for loop

Step-by-step approach:

  • Create an empty dictionary to store the grouped tuples
  • Loop through the tuples in the list
    • Get the second element of the tuple
    • If the key is not already in the dictionary, add it to an empty list as value
    • Append the current tuple to the list corresponding to the key in the dictionary
  • Convert the dictionary values to lists and store in res
  • Printing result

Below is the implementation of the above approach:

Python3




# initialize list
test_list = [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
 
# printing original list
print("The original list : " + str(test_list))
 
# create an empty dictionary to store the grouped tuples
grouped_dict = {}
 
# loop through the tuples in the list
for tup in test_list:
    # get the second element of the tuple
    key = tup[1]
    # if the key is not already in the dictionary, add it with an empty list as value
    if key not in grouped_dict:
        grouped_dict[key] = []
    # append the current tuple to the list corresponding to the key in the dictionary
    grouped_dict[key].append(tup[0])
 
# convert the dictionary values to lists and store in res
res = [v for k, v in grouped_dict.items()]
 
# printing result
print("The list after grouping by value : " + str(res))


Output

The original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
The list after grouping by value : [[1, 2], [6], [5, 6, 8]]

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



Last Updated : 13 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads