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

Get notified of the best deals on our WordPress themes.

You May Also Like
Python Bool()

Python bool()

Table of Contents Hide bool() Syntax bool() Parametersbool() Return ValueExample of bool() function in Python Python’s bool() function converts a given value into Boolean(True or False) using the standard truth testing…
View Post
Python String Isdecimal()

Python String isdecimal()

Table of Contents Hide isdecimal() Syntaxisdecimal() Parametersisdecimal() Return ValueExample 1: Working of isdecimal()Example 2: String Containing digits and Numeric Characters The Python String isdecimal() method is a built-in function that…
View Post
Python Bytes()

Python bytes()

Table of Contents Hide bytes() Syntax bytes() Parametersbytes() Return ValueExample 1: Create a byte of a given integer sizeExample 2: Convert string to bytesExample 3: Convert iterable list to bytesExample 4:…
View Post