Change language

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 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method