Python | Finding frequency in list of tuples
In python we need to handle various forms of data and one among them is list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the 1st element in list of tuple which can be extended to any index. Let’s discuss certain ways in which this can be performed.
Method #1 : Using map() + count() The map function can be used to accumulate the indices of all the tuples in a list and the task of counting the frequency can be done using the generic count function of python library.
Method #2 : Using Counter() + list comprehension List comprehension performs the task of getting the first element of the tuples and the counting part is handled by Counter function of collection library.
Method #3 : Dictionary comprehension and the get() method
To use dictionary comprehension and the get() method to find the frequency of the element ‘Geeks’ in the list of tuples test_list, you can do the following:
If the element is already in the dictionary, the get() method returns its current value, and this value is incremented by 1. This allows us to count the frequency of each element in the list of tuples.
Time complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using map() + operator.countOf() method
The map function can be used to accumulate the indices of all the tuples in a list and the task of counting the frequency can be done using the operator.countOf function of python library.
The original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)] The frequency of element is : 2
Time complexity: O(n*n)
Auxiliary Space: O(1)