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:

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

﻿

Python: Tips of the Day

Inserting if statements using conditional list comprehensions:

x = [1, 2, 3, 4, 5, 6]
result = []
for idx in range(len(x)):
if x[idx] % 2 == 0:
result.append(x[idx] * 2)
else:
result.append(x[idx])
result

Output:

[1, 4, 3, 8, 5, 12]
[(element * 2 if element % 2 == 0 else element) for element in x]

Output:

[1, 4, 3, 8, 5, 12]
[element * 2 for element in x if element % 2 == 0]

Output:

[4, 8, 12]