If you only want a single item's count, use the count method:
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
Important: this is very slow if you are counting multiple different items
Each count call goes over the entire list of n elements. Calling count in a loop n times means n * n total checks, which can be catastrophic for performance.
If you want to count multiple items, use Counter, which only does n total checks.
Looking for different counting patterns to add to my counting arsenal. Any code is appreciated!!
Specifically I want to make a "counting" dictionary as I think this would be the most practical as it stores the key and values. It iterates over a list or string, puts the iterated item into the dict and increments the item's value.
python - How do I count the occurrences of a list item? - Stack Overflow
How to count items in a list without using any built-in functions.
Python - Count elements in list - Stack Overflow
how do I count a certain key value in a list python
Videos
If you only want a single item's count, use the count method:
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
Important: this is very slow if you are counting multiple different items
Each count call goes over the entire list of n elements. Calling count in a loop n times means n * n total checks, which can be catastrophic for performance.
If you want to count multiple items, use Counter, which only does n total checks.
Use Counter if you are using Python 2.7 or 3.x and you want the number of occurrences for each element:
>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})
Let's says a create a list in Python: 1, 2, 3, 4, 5.
Without using any built-in functions like count() or len(), how would I found out how many items are in the list?