Calculate the frequency of elements in a tuple

In this python tuple program, we will calculate the frequency of elements in a tuple.

Steps to solve the program
  1. Take a tuple as input and create an empty dictionary.
  2. Use for loop to iterate over each character from the tuple.
  3. If a character is not in the dictionary then add that character as a key and 0 as its value.
  4. If the character is already in the list then add 1 to the value.
  5. Print the output.
				
					tup = ('a','b','c','d','b','a','b')
print("Original tuple: ",tup)
d = {}
for char in tup:
    if char not in d:
        d[char] = 0
    if char in d:
        d[char] += 1
print("Frequency count : ",d)
				
			

Output :

				
					Original tuple:  ('a', 'b', 'c', 'd', 'b', 'a', 'b')
Frequency count :  {'a': 2, 'b': 3, 'c': 1, 'd': 1}
				
			

sort a list of tuples by the length of the tuple.

filter out tuples that have more than 3 elements.

Leave a Comment