Change language

How to count the total number of occurrences of an object in a Python list?

You can use the list class count function to count the occurrences of an object in a Python list. Only use this if you only want to read one object. It finds the total number of the object you are passing in the list to which it is being called. 

Example

""" ["red", "blue", "red", "red", "blue"]. count ("red") 3 

If you want to get a count for all objects in the list, you better use counter from collections. It counts the frequency of all objects in the given list and returns them as a dictionary with keys as objects and values ​​as their number in the list.



 from collections import Counter my_list = ["red", "blue", "red", "red", "blue"] print (Counter (my_list)) 

Output

This will give the output &



 Counter ({’blue’: 2,’ red’: 3}) 



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