Python List count()

Python List count() is a built-in function that returns the number of times the specified element occurs in the list.

In this tutorial, we will learn about the Python list count() method with the help of examples.

Syntax of List count() 

The syntax of the count() method is:

list.count(element)

count() Parameters

The count() method takes a single parameter.

  • element – The element or value that needs to be counted in the list.

If more than one element is passed to the count() method, it will throw TypeError: count() takes exactly one argument (2 given) exception.

Return Value from List count()

The count() method returns the number of times an element has appeared in the list.

Example 1: Use of count()

In the below example the count() method returns the number of times the elements appears in the list.

# list of cars
cars = ['Benz','BMW','Ford','Ferrari','volkswagen','BMW']
numbers= [1,5,2,5,7,1,3,3,1,6]

# BWM Count in list
bmwCount = cars.count('BMW')
print("total no BMW count is = ",bmwCount)

# number count in list
numCount = numbers.count(1)
print("The count of number 1 is = ",numCount)

# if you give number in string format
numCount = numbers.count('3')
print("The count of number 3 is= ",numCount)

Output

total no BMW count is =  2
The count of number 1 is =  3
The count of number 3 is=  0

Example 2: Count Tuple and List Elements Inside List

# list of cars
cars = ['Benz',('volkswagen','BMW'),'Ford','Ferrari',('volkswagen','BMW')]
numbers= [1,(1,3),5,7,(1,3),3,1,6,(1,3)]

# BWM Count in list
bmwCount = cars.count(('volkswagen','BMW'))
print("total no BMW, volkswagen count is = ",bmwCount)

# number count in list
numCount = numbers.count((1,3))
print("The count of number 1,3  is = ",numCount)

Output

total no BMW, volkswagen count is =  2
The count of number 1,3  is =  3
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Python Dir()

Python dir()

Table of Contents Hide dir() Syntax dir() Parametersdir() Return ValueExample 1: How dir() works?Example 2: When no parameters are passed to dir() method with and without importing external libraries.Example 3: When a module…
View Post
Python All()

Python all()

Table of Contents Hide all() Syntaxall() Parametersall() Return ValueDifference between any() and all() functions in PythonExample 1 – Using all() function on Python ListsExample 2 – Using all() function on…
View Post
Python Jsonpath

Python JSONPath

Table of Contents Hide JSONPath Library in PythonInstalling jsonpath-ng ModuleJsonpath operators:Parsing a Simple JSON Data using JSONPathParsing a Json Array using JSONPath Expression JSONPath is an expression language that is…
View Post