Python List count() Method



The Python List count() method is used to count the number of times an object occurs in a list. This method is same as the Python string count() method, in which the number of occurrences of a character in a string is obtained. However, unlike the string method, this list method does not raise a TypeError whenever its argument is not present in the list. This is because a list in Python can hold multiple data types in contrast to a string.

For example, consider a list with either multiple data types or similar data types, say [1, 'a', 12, 'a', 1]. The count of element '1' would be 2, element 'a' would also be 2 and the count of element '12' would be 1.

Syntax

Following is the syntax for the Python List count() method −

list.count(obj)

Parameters

  • obj − This is the object to be counted in the list.

Return Value

This method returns count of how many times obj occurs in list.

Example

The following example shows the usage of the Python List count() method.

aList = [123, 'xyz', 'zara', 'abc', 123]
print("Count for 123 : ", aList.count(123))
print("Count for zara : ", aList.count('zara'))

When we run above program, it produces following result −

Count for 123 :  2
Count for zara :  1

Example

The method differentiates the data types in the list. For example, if a number is present in the list in the form of both an integer and a string, the count() method only counts the element in the specified data type and ignores the other. Let us look at the program below.

aList = [12, 'as', 12, 'abc', '12', 12]

# Counting the occurrences of integer 12
print("Count for 12 : ", aList.count(12))

# Counting the occurrences of string 12
print("Count for '12' : ", aList.count('12'))

When we run above program, it produces following result −

Count for 12 :  3
Count for '12' :  1

Example

Unlike the String count() method, the List count() method does not raise a TypeError when an argument of a different type is not present in it. Here, when we try to count the number of times the integer '127' occurs in a list, the method returns 0 as it is not present in the list.

aList = ['ed', 'alex', 'jacob', 'kai', 'john']
print("Count for 127 : ", aList.count(127))

When we run above program, it produces following result −

Count for 127 :  0
python_lists.htm
Advertisements