Sometimes, while working with Python records, we can have a problem in which we need to perform grouping of elements of tuple by similar Kth index element. This kind of problem can have application in web development domain. Let’s discuss certain way in which this task can be performed.
Input : test_list = [(4, 5), (3, 2), (2, 2), (1, 2), (5, 5)], K = 0
Output : [((1, 2), ), ((2, 2), ), ((3, 2), ), ((4, 5), ), ((5, 5), )]
Input : test_list = [(4, 5), (3, 2), (2, 2)], K = 1
Output : [((2, 2), (3, 2)), ((4, 5), )]
Method : Using
groupby() + itemegetter() + generator expression
The combination of above functions can be used to solve this problem. In this, we perform the task of grouping the elements from Kth index extracted using itemgetter and generator expression is used to bind whole logic together.
The original list is : [(4, 5), (3, 2), (2, 2), (1, 2), (5, 5)] Tuples after grouping : [((1, 2), (2, 2), (3, 2)), ((4, 5), (5, 5))]
- Python | Find the tuples containing the given element from a list of tuples
- Python - Filter Tuples by Kth element from List
- Python | Remove duplicate tuples from list of tuples
- Python | Remove tuples from list of tuples if greater than n
- Python | Remove tuples having duplicate first value from given list of tuples
- Python | Count tuples occurrence in list of tuples
- Python | Combining tuples in list of tuples
- Python | Convert string tuples to list tuples
- Python | How to Concatenate tuples to nested tuples
- Python - Filter all uppercase characters Tuples from given list of tuples
- Python program to find Tuples with positive elements in List of tuples
- Python program to find tuples which have all elements divisible by K from a list of tuples
- Python | Group by matching second tuple value in list of tuples
- Python | Group tuples in list with same first value
- Python - Element Index in Range Tuples
- Python - Unique Kth positioned tuples
- Python - Group records by Kth column in List
- Python - Closest Pair to Kth index element in Tuple
- Python - Access element at Kth index in given String
- Python | Index Maximum among Tuples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.