Python | Finding a Frequency in a List of Tuples

Method # 1: Using map () + count ()
The map function can be used to accumulate the indices of all tuples in a list, and the task of counting the frequency can be done using the Python library`s generic count function.

# Python3 demo code
# search for frequency in a list of tuples
# using map () + count ()

  
# initializing the list of tuples

test_list = [( ` Geeks` , 1 ), ( `for` , 2 ), ( `Geeks` , 3 )]

  
# print original list

print ( "The original list is:" + str (test_list))

 
# using the map () + count ()
# search for frequency in the list of tuples

res = list ( map ( lambda i: i [ 0 < code class = "plain">], test_list)). count ( `Geeks` )

 
# print result

print ( "The frequency of element is:" + str (res))

Exit:

 The original list is: [(`Geeks`, 1), (` for`, 2), (`Geeks` , 3)] The frequency of element is: 2 

Method # 2: Using Counter () + list comprehension
List comprehension function performs the task of getting the first element of tuples, and the counting part is processed by the Counter function of the collection library.

# Python3 code for demonstration
# search for frequency in a list of tuples
# using Counter () + list comprehension

from collections import Counter

 
# initialize the list of tuples

test_list = [( `Geeks` , 1 ), ( `for` , 2 ), ( ` Geeks` , 3 )]

 
# print origin list

print ( "The original list is: " + str (test_list))

 
# using Counter () + list comprehension
# find frequency in list of tuples

res = Counter (i [ 0 ] for i in test_list)

 
# print result

print ( "The frequency of element is:" str (res [ `Geeks` ]))

Output:

 The original list is: [(`Geeks`, 1), (` for`, 2), (`Geeks`, 3)] The frequency of element is: 2