TGViewer
Learn Python Coding Learn Python Coding @pythonre · 40.8K subscribers
Post #9225 1.02K
A bit of Python basics. Day 7. Counting the number of occurrences of an element

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
  • 👍 4
  • ❤ 1
More from @pythonre
  1. Oct 10, 2026📚 Download 10 Python books for FREE: 1. Think Python — O’Reilly https://t.co/X7y3pX68IW 2…
  2. Oct 7, 2026Python Lists: A Quick Reference 🐍 * Definition: Lists are ordered, mutable collections th…
  3. Oct 7, 2026📱 270 tools for Python developers The repository contains: 🫡 Linters and formatters; 🫡…
  4. Oct 7, 2026Hands On Python Data Science - Data Science Bootcamp Master Python for Data Science with R…
  5. Oct 6, 2026Post #9851
  6. Oct 6, 2026Python For Beginners Course In-Depth Python: A Comprehensive Introduction to Fundamental P…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →