If you need to find out how many times an element appears in an iterable collection, you can use the
Counter class from the collections module. Counter() returns a dictionary with the number of times each element appears in the sequence. Let's say we want to find out how many times the name Peter appears in the following list. We can use Counter(). See below:from collections import Counter
list1 = ['John', 'Kelly', 'Peter', 'Moses', 'Peter']
count_peter = Counter(list1).get("Peter")
print(f'The name "Peter" appears in the list '
f'{count_peter} times.')
Output:
The name "Peter" appears in the list 2 times.Another way to do this is with a regular
for loop. We create a count variable and increase it by 1 each time we find the name Peter in the sequence. This is a naive approach. See below:list1 = ['John', 'Kelly', 'Peter', 'Moses', 'Peter']
# Create a count variable
count = 0
for name in list1:
if name == 'Peter':
count +=1
print(f'The name "Peter" appears in the list'
f' {count} times.')
Output:
The name "Peter" appears in the list 2 times.Lists and other iterable data structures in Python have a built-in
count() method, which allows us to count the number of occurrences of a specific element. We can use count() to count how many times Peter appears in the list.list1 = ['John', 'Kelly', 'Peter', 'Moses', 'Peter']
print(f'The name "Peter" appears in the list '
f'{list1.count("Peter")} times.')
Output:
The name "Peter" appears in the list 2 times.👉 https://t.me/DataScience4