Counting Items in a List in Python
To find the number of matches of an element in a list, we use the count
method. In its parameter, we specify the element we need:
lst = [1, 2, 1, 3]
print(lst.count(1)) # 2
Let's try to find an element that is not in the list:
lst = [1, 2, 1, 3]
print(lst.count(4)) # 0
The following code is given:
lst = ['a', 'b', 'c', 'd']
print(lst.count('c'))
Tell me what will be output to the console.
The following code is given:
lst = ['1', 'b', '2', 'd']
print(lst.count(1))
Tell me what will be output to the console.
The following code is given:
lst = ['ab', '12', 2, 'cd', 1, 2]
print(lst.count(2))
Tell me what will be output to the console.