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)))
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)))
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.
Output:
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.
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer