ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.