w3resource

Python List: count() Method

count() Method

The count() method is used to get the number of times a specified element appears in a given list.

Visual Explanation:

Python List: count() method

Syntax:

list.count(element)

Parameter:

  • element - Required. The element is to be counted.. Type -> any type (string, number, list, tuple, etc.).

Return value from count() method

The number of times an element appears in the list is returned.

Example 1: Use of count() method


# colors list
colors = ['Red', 'Green', 'Black', 'Red', 'Green']
print("Original list:") 
print(colors)  
print("Number of times the value 'Red' appears in the colors list:")
ctr = colors.count("Red")
print(ctr)

Output:

Original list:
['Red', 'Green', 'Black', 'Red', 'Green']
Number of times the value 'Red' appears in the colors list:
2

Example 2: Count tuple and list elements inside list


nums = [[1,2], [1,2,3], [3,4,5], [1,2]] 
print("Original list:")
print(nums)
print("Number of times the list '[1,2]' appears in the said list:")
ctr = nums.count([1,2])
print(ctr)

Output:

Original list:
[[1, 2], [1, 2, 3], [3, 4, 5], [1, 2]]
Number of times the list '[1,2]' appears in the said list:
2

Python Code Editor:

Previous: Python List copy() Method.
Next: Python List extend() Method.

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.