Q:

Python program to find the frequency of all tuple elements

belongs to collection: Python Tuple Programs

0

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.

All Answers

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

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}

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 perform cross pairing in tuple l... >>
<< Python program to find tuples with positive elemen...