ADVERTISEMENT
ADVERTISEMENT

Python program to find the frequency of all tuple elements

In this program, we have a tuple and we need to find the frequency of all tuple elements.
Submitted by Shivang Yadav, on September 02, 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)

Finding the frequency of all tuple elements

To find the frequency of all elements, we need to count each element of the tuple and then return each of them with frequency.

Method 1:

A method to perform this task is by using the default dictionary where we will map each element with a key. And the frequencies will be updated based on occurrence.

# Python program to find the frequency 
# of elements of a tuple 

from collections import defaultdict

# Creating the tuple and printing its frequency
myTuple = (0, 2, 3, 4, 1, 0, 1, 0, 2, 6, 3, 8, 0, 3)
print("Tuple : " + str(myTuple))

tupFreq = defaultdict(int)
for ele in myTuple:
	tupFreq[ele] += 1

# Printing tuples and frequencies : 
print("Frequency of Tuple Elements : " + str(dict(tupFreq)))

Output:

Tuple : (0, 2, 3, 4, 1, 0, 1, 0, 2, 6, 3, 8, 0, 3)
Frequency of Tuple Elements : {0: 4, 2: 2, 3: 3, 4: 1, 1: 2, 6: 1, 8: 1}

Method 2:

Another method is using the counter() method to count the occurrence frequency of elements in the tuple and store them in a dictionary.

# Python program to find the frequency 
# of elements of a tuple 

from collections import Counter

# Creating the tuple and printing its frequency
myTuple = (0, 2, 3, 4, 1, 0, 1, 0, 2, 6, 3, 8, 0, 3)
print("Tuple : " + str(myTuple))

tupFreq = dict(Counter(myTuple))

# Printing tuples and frequencies : 
print("Frequency of Tuple Elements : " + str(dict(tupFreq)))

Output:

Tuple : (0, 2, 3, 4, 1, 0, 1, 0, 2, 6, 3, 8, 0, 3)
Frequency of Tuple Elements : {0: 4, 2: 2, 3: 3, 4: 1, 1: 2, 6: 1, 8: 1}

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.