Finding the frequency of a given Datatype in a Python tuple


The tuple is a popular datatype of Python that represents the collection of objects or elements separated by commas. The frequency of data type defines the total number of counts of a specific variable type. Python has four primitive variable types: integer, float, boolean, and string. In Python, we have some built-in functions such as type(), isinstance(), filter(), lambda, len(), and list() will be used to Find the frequency of a given Datatype in a Python tuple.

Syntax

The following syntax is used in the examples-

type()

The type() is an in-built function in Python that returns the type object.

isinstance()

The isinstance() is an in-built function in Python that integrates the value with a given type.

filter()

The filter() method is applied when it filters the items based on specific conditions. In simple terms, it allows users to iterate those elements that are extracted to satisfy the condition.

lambda

The function lambda offers a shortcut for declaring brief anonymous functions using the lambda keyword. The lambda functions behave when expressed with the def keyword.

len()

The len() is an in-built function in Python that returns the object's length.

list()

The list() is an in-built function in Python that converts any value into the form of a list.

Using Simple for Loop

In this program, the variable count store the initial value as 0 that will be used during the counter incrementation. Then use the for loop where variable i iterate through the given input tuple i.e. t. Next, the if-statement set the condition of equivalence between type()[that returns the specific type ] and d_type. Now the variable count increment by 1 which find the frequency of specific data types. Finally, function returns generate the result.

Example

# recursive function
def total_freq(t, d_type):
    count = 0
    for i in t:
        if type(i) == d_type:
            count += 1
    return count
# The tuple elements
my_tup = (5, 8.9, "Box", 3.3, "CAR", 7, 1.0)
# Set the datatype as float
datatype = float
# Calling function
freq = total_freq(my_tup, datatype)
print("The frequency of", datatype, ":\n", freq)

Output

 The frequency of <class 'float'> : 3

Using list Comprehension

In the following example, we will start the program by defining a function named data_freq_count() that accepts two parameters- t and datatype to fetch the value from the variables my_tup and d_type through a function call. Next, function return uses built-in function sum() that generate the value of 1, where the variable item iterates through the variable t. Using an if-statement it set the condition as type() equivalent to the variable datatype which finds the element belonging to a specific data type. Finally, it will display the result.

Example

def data_freq_count(t, datatype):
    return sum(1 for item in t if type(item) == datatype)
my_tup = (1, 'A', 2, 'B', 3.9, 15, 0, 'True')
# Set the datatype as an integer
d_type = int
freq = data_freq_count(my_tup, d_type)
print("The total count of integer frequency is ", freq)

Output

 The total count of integer frequency is  4

Using isinstance() Function

In the following example, the variable cnt initialize with initial value of 0 that will be used during the iteration of the input tuple. Using for loop, the variable i iterate each individual tuple element from variable t. Next, it will use the if-statement to set the condition as an in-built function isinstance() that accepts two parameters- i and d that compare the value of specific datatype present in a given tuple. Then increment the variable cnt by 1 with the help of += operator and return the result of the program.

Example

def data_freq_count(t, d):
    cnt = 0
    for i in t:
        if isinstance(i, d):
            cnt += 1
    return cnt
# The input tuple elements
my_tup = (5, 'abc', 2, 4.8, 7.2, 'is', 4.0)
# Set the datatype as string
d_type = str
# Calling function
freq = data_freq_count(my_tup, d_type)
print("The total frequency of string datatype:", freq)

Output

 The total frequency of string datatype: 2

Using filter() Function

The program uses two input variables- my_tuple and d_type to store the value as a tuple and bool datatype respectively. The value of these variables will be fetched by the function named data_freq_count() which accepts two parameters- t and d to work on the operation of datatype frequency. Then it will use the built-in filter() that accept lambda as a parameter to calculate the total count of specific data type. Next, function return will use the built-in function len() and list() to generate the output.

Example

def data_freq_count(t, d):
    filtered_tuple = filter(lambda item: type(item) == d, t)
    return len(list(filtered_tuple))
# Initialize the tuple 
my_tuple = (5, "PYTHON", 40.0, "JAVA", 5.0, True, False)
d_type = bool
# Calling function
freq = data_freq_count(my_tuple, d_type)
print("The frequency of float datatype:", freq)

Output

The frequency of float datatype: 2

Conclusion

We discussed the various methods to set the specific datatype and find its frequency. There are various built-in functions used such as filter(), type(), etc fulfilling the need of specific conditions and operations. This type of program can be taken as a reference for data manipulation and data analysis such as statistical analysis and ML applications.

Updated on: 16-Aug-2023

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements