In this python tuple program, we will assign the frequency of tuples to each tuple.
Steps to solve the program
- Take a list of tuples as input and create an empty dictionary.
- Use for loop to iterate over each tuple from the list.
- If a tuple is not in the dictionary then add that tuple as a key and 0 as its value.
- If the tuple is already in the list then add 1 to the value.
- Print the output.
l = [('s','q'),('t','o','o','l'),('p','y'),('s','q')]
print("Original list of tuples: ",l)
d = {}
for tup in l:
if tup not in d:
d[tup] = 0
if tup in d:
d[tup] += 1
print("Frequency count : ",d)
Output :
Original list of tuples: [('s', 'q'), ('t', 'o', 'o', 'l'), ('p', 'y'), ('s', 'q')]
Frequency count : {('s', 'q'): 2, ('t', 'o', 'o', 'l'): 1, ('p', 'y'): 1}