Group a list by the values in Python

Here we will learn how to group a list by the values in Python.

List grouping based on values converts a list to the lists of list according to the values taken as the second element. The first element will be string followed by its values.

For example,

Consider the marks obtained by 8  students in Computer Science. Now we have to group the students who have obtained the same marks.

[[“Aisha”,30], [“Bhavs”,40],[“Cat”, 35],[“Sam”,40],[“Andre”,35],[“Trina”,40],[“Robbie”,30],[“Beck”,35]] will give output as [[‘Aisha’, ‘Robbie’], [‘Cat’, ‘Andre’, ‘Beck’], [‘Bhavs’, ‘Sam’, ‘Trina’]]

In this tutorial, I will take a tour of how to group a list using 2 methods.

Group a list in Python using itemgetter and groupby function

Here, We import 2 functions in Python namely “itemgetter” and “groupby”

itemgetter : builds a callable which assumes an iterable object as the input given, and gets the n-th item out of it.

You can refer to https://docs.python.org/3/howto/sorting.html to get more ideas about itemgetter function.

groupby: takes up a few mixtures of object splitting, function applying, and blending the results.

 

from operator import itemgetter
from itertools import groupby

list = [["Aisha",30], ["Bhavs",40],["Cat", 35],["Sam",40],["Andre",35],["Trina",40],["Robbie",30],["Beck",35]]
list.sort(key=itemgetter(1))

res = [[x for x,y in z]
       for k,z in  groupby(list,key=itemgetter(1))]

print(res)

Here,  we are grouping a list based on their values.

Output

[['Aisha', 'Robbie'], ['Cat', 'Andre', 'Beck'], ['Bhavs', 'Sam', 'Trina']]

List grouping in Python using set function

In this method, there is no need of importing any modules. We just extract all the values in a list and store the unique values using the set function. Later we iterate through the unique values and if the values of the other list are matching, then we append the list to the result.

Finally, we print the result.

stu_details = [["Aisha",30], ["Bhavs",40],["Cat", 35],["Sam",40],["Andre",35],["Trina",40],["Robbie",30],["Beck",35]]

all_values = [list[1] for list in stu_details]
unique_values = set(all_values)

result = []
for value in unique_values:
  this_group = []
  for list in stu_details:
    if list[1] == value:
      this_group.append(list[0])
  result.append(this_group)

print(result)

As we can see Aisha and Robbie have scored 30 marks, so we can group them together. Similarly, Bhavs, Sam, and Trina have scored 40 marks and those 3 are grouped together. So we are grouping the student’s lists based on their marks obtained.

Output

[['Bhavs', 'Sam', 'Trina'], ['Cat', 'Andre', 'Beck'], ['Aisha', 'Robbie']]

By the following two methods, You can group a list based on the values given.

Also read: Random Singly Linked List Generator using Python

Leave a Reply

Your email address will not be published. Required fields are marked *