Python program to assign frequency to tuples

Here, we have a list of tuples consisting of values. We need to find the frequency of occurrence of each tuple in the list and assign it to the last in Python.
Submitted by Shivang Yadav, on August 24, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

Example:

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

Assigning frequency to Tuples

In our program, we have a list of tuples and we need to count the number of tuples and then assign the frequency to the last value of the tuple.

Input:
tupList = [(4, 1), (3, 3), (4, 1), (5, 7), (3, 3), (4, 1)]

Output:
freqList = [((4, 1), 3), ((3, 3), 2), ((4, 1), 2)]

To perform the given task in python, we have multiple methods as we just need to count the number of occurrences of each tuple and then add it as the last element for the tuple.

Let's see different methods to perform the task in Python.

Method 1:

One method to solve the problem is by counting the occurrence of each tuple in the list using the counter() method then this frequency is fetched using the items() method. Using the list comprehension and * operator, we will initialize tuple list with frequency. 

Program to assign the frequency to tuples in Python

# Python program to assign frequency
# to tuples

from collections import Counter

# Creating and printing the list of tuple
tupList = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
print("The list of Tuples is : " + str(tupList))

# Counting occurences and adding it to the tuples
freqTuple = [(key, val) for key, val in Counter(tupList).items()]

# Printing results
print("List of tuples with frequency added at end :" + str(freqTuple))

Output:

The list of Tuples is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9,), (2, 7)]
List of tuples with frequency added at end :[((6, 5, 8), 3), ((2, 7), 2), ((9,), 1)]

Note: We can use the most_common() method instead of the items() method to count the tuples.

Python Tuple Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.