×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

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 »



Related Programs

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.