0% found this document useful (0 votes)
50 views

Group A List by The Values in Python - CodeSpeedy

This document discusses two methods for grouping a list of student names and test scores by score in Python. The first method uses the itemgetter and groupby functions to sort the list by score and then group elements with the same score. The second method extracts the unique scores, iterates through them and appends names with matching scores to the result. Both methods produce a grouped list with sublists of names for each unique score.

Uploaded by

Sathi Natarajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Group A List by The Values in Python - CodeSpeedy

This document discusses two methods for grouping a list of student names and test scores by score in Python. The first method uses the itemgetter and groupby functions to sort the list by score and then group elements with the same score. The second method extracts the unique scores, iterates through them and appends names with matching scores to the result. Both methods produce a grouped list with sublists of names for each unique score.

Uploaded by

Sathi Natarajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Group a list by the values in Python - CodeSpeedy https://www.codespeedy.com/group-a-list-by-the-values-in-p...

CodeSpeedy (https://www.codespeedy.com/)

Menu

Group a list by the values in Python


By Arpitha (https://www.codespeedy.com/author/arpitha_h/)

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.

1 of 6 11/4/22, 20:58
Group a list by the values in Python - CodeSpeedy https://www.codespeedy.com/group-a-list-by-the-values-in-p...

You can refer to https://docs.python.org/3/howto/sorting.html


(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.

1. from operator import itemgetter


2. from itertools import groupby
3.
4. list = [["Aisha",30], ["Bhavs",40],["Cat", 35],["Sam",40],["Andre",35],[
5. list.sort(key=itemgetter(1))
6.
7. res = [[x for x,y in z]
8. for k,z in groupby(list,key=itemgetter(1))]
9.
10. print(res)

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

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

Run this code online (https://www.codespeedy.com/online-python-


compiler?code=from+operator+import+itemgetter%0D%0Afrom+itertools+import+groupby
%0D%0A%0D%0Alist+%3D+%5B%5B%22Aisha%22%2C30%5D%2C+%5B%22Bhavs
%22%2C40%5D%2C%5B%22Cat%22%2C+35%5D%2C%5B%22Sam%22%2C40
%5D%2C%5B%22Andre%22%2C35%5D%2C%5B%22Trina%22%2C40%5D%2C
%5B%22Robbie%22%2C30%5D%2C%5B%22Beck%22%2C35%5D%5D
%0D%0Alist.sort%28key%3Ditemgetter%281%29%29%0D%0A%0D%0Ares+%3D+
%5B%5Bx+for+x%2Cy+in+z%5D%0D

2 of 6 11/4/22, 20:58
Group a list by the values in Python - CodeSpeedy https://www.codespeedy.com/group-a-list-by-the-values-in-p...

%0A+++++++for+k%2Cz+in++groupby%28list%2Ckey%3Ditemgetter%281%29%29
%5D%0D%0A%0D%0Aprint%28res%29&version=4&stdinputs=)

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.

1. stu_details = [["Aisha",30], ["Bhavs",40],["Cat", 35],["Sam",40],["Andre"


2.
3. all_values = [list[1] for list in stu_details]
4. unique_values = set(all_values)
5.
6. result = []
7. for value in unique_values:
8. this_group = []
9. for list in stu_details:
10. if list[1] == value:
11. this_group.append(list[0])
12. result.append(this_group)
13.
14. print(result)

Run it online (https://www.codespeedy.com/online-python-


compiler?code=stu_details+%3D+%5B%5B%22Aisha%22%2C30%5D%2C+
%5B%22Bhavs%22%2C40%5D%2C%5B%22Cat%22%2C+35%5D%2C%5B%22Sam
%22%2C40%5D%2C%5B%22Andre%22%2C35%5D%2C%5B%22Trina%22%2C40
%5D%2C%5B%22Robbie%22%2C30%5D%2C%5B%22Beck%22%2C35%5D%5D
%0D%0A%0D%0Aall_values+%3D+%5Blist%5B1%5D+for+list+in+stu_details%5D%0D
%0Aunique_values+%3D+set%28all_values%29%0D%0A%0D%0Aresult+%3D+%5B%5D
%0D%0Afor+value+in+unique_values%3A%0D%0A++this_group+%3D+%5B%5D
%0D%0A++for+list+in+stu_details%3A%0D%0A++++if+list%5B1%5D+%3D%3D+value
%3A%0D%0A++++++this_group.append%28list%5B0%5D%29

3 of 6 11/4/22, 20:58
Group a list by the values in Python - CodeSpeedy https://www.codespeedy.com/group-a-list-by-the-values-in-p...

%0D%0A++result.append%28this_group%29%0D%0A%0D%0Aprint%28result%29&
version=4&stdinputs=)
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
1. [['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


(https://www.codespeedy.com/random-singly-linked-list-generator-using-
python/)

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

Comment *

4 of 6 11/4/22, 20:58
Group a list by the values in Python - CodeSpeedy https://www.codespeedy.com/group-a-list-by-the-values-in-p...

Name *

Email *

Post Comment

« Random Binary Tree Generator using Python Check if two Date Ranges Overlap or not in Java
(https://www.codespeedy.com/random-binary-tree- (https://www.codespeedy.com/check-if-two-date-
generator-using-python/) ranges-overlap-or-not-in-java/) »

Search

Latest Articles

• Merge two arrays without duplicates in Python

• Retrieve value from a dictionary in Swift

• scipy.signal.butter and its usage in Python

• Event Handling in Pygame Python

• Add a new row to an empty numpy array in Python

5 of 6 11/4/22, 20:58
Group a list by the values in Python - CodeSpeedy https://www.codespeedy.com/group-a-list-by-the-values-in-p...

Related Posts

▪ How to Get the Number of Elements in a Python List


▪ Convert a Dictionary into a List in Python
▪ Split a list into evenly sized chunks in Python

• Python (https://www.codespeedy.com/category/python/) | Java (https://www.codespeedy.com/category


/java/) | C++ (https://www.codespeedy.com/category/cpp-programming/) |Machine Learning
(https://www.codespeedy.com/category/machine-learning/) | JavaScript (https://www.codespeedy.com
/category/javascript/)

• Privacy policy (https://www.codespeedy.com/privacy-policy/) | Contact (https://www.codespeedy.com


/contact-us/) | About (https://www.codespeedy.com/about-us/)

By continuing to visit our website, you agree to the use of cookies as described
in our Cookie Policy (https://www.codespeedy.com/cookie-policy/)

6 of 6 11/4/22, 20:58

You might also like