Q:

Python program to print all group tuples by Kth index element

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered set of values enclosed in square brackets []

list = [3 ,1,  5, 7]

List of tuples is a list whose each element is a tuple.

tupList = [("python", 7), ("learn" , 1), ("programming", 7), ("code" , 3)]

Now, let's get back to our topic where we will pair combinations of tuples.

Grouping tuples by Kth Index Element

We will be grouping all the kth index elements on the list based on the kth index element of the list. In Python, we have multiple methods or ways that can be used to do the task for us.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by grouping the elements of tuples of the list based on the given index k using the groupby() method. Additionally, we will be using the itemgetter and generator expression.

# Python program to print all group tuples 
# by Kth Index Element

from operator import itemgetter
from itertools import groupby

# Creating and printing the list of tuples
myTupleList = [(4, 1), (6, 5), (3, 1), (6, 6), (1, 1), (5,9), (2, 5)]
print("Elements of list of tuples are " + str(myTupleList))
K = 0

# Grouping tuples by kth index Element 
myTupleList.sort()
groupTupleList = list(tuple(sub) for idx, sub in groupby(myTupleList, key = itemgetter(K)))

# printing resultant list
print("List of grouped tuples is " + str(groupTupleList))

Output:

Elements of list of tuples are [(4, 1), (6, 5), (3, 1), (6, 6), (1, 1), (5, 9), (2, 5)]
List of grouped tuples is [((1, 1),), ((2, 5),), ((3, 1),), ((4, 1),), ((5, 9),), ((6, 5), (6, 6))]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to alternate elements operation on ... >>
<< Python program to print all pair combinations of e...