My Coding > Programming language > Python > Python FAQ > Python: How to count objects in the list

Python: How to count objects in the list

Counting of objects in the list is a very common task, and now I will show few approaches for this counting

Traditional counting technique

This is valid way of counting, but can be considered as a “bad python practice”, so should be avoided.


lst = [2, 4, 5, 3, 4, 5, 2, 2] # list for counting
count = {}                     # dictionary for results
for x in lst:
    if x not in count:
        count[x] = 0
    count[x] += 1
print(count)                   # {2: 3, 4: 2, 5: 2, 3: 1}

Pythonish way for counting

In Python you can count list content in few different ways

Count with SET

The main idea is to create a unique set of all keys and then count them


lst = [2, 4, 5, 3, 4, 5, 2, 2] # list for counting
count = {}                     # dictionary for results 
s = set(lst)                   # unique set of elements
for x in s:
    count[x] = lst.count(x)
print(count)                   # {2: 3, 4: 2, 5: 2, 3: 1}

Count with default dictionary defaultdict

The main idea of this way is to create defaultdict with creating every new elemnt with defauult value = 0


from collections import defaultdict # defaul dictionary
lst = [2, 4, 5, 3, 4, 5, 2, 2] # list for counting
count = defaultdict(lambda: 0) # dictionary for results 
for x in lst:
    count[x] += 1
print(count)
#defaultdict( at 0x7f9455d88e18>, {2: 3, 4: 2, 5: 2, 3: 1})

Count with get() method

Method get() allow to use dictionary with any key, and if this key is not present, then get() returns default value, rather than throw an error.


lst = [2, 4, 5, 3, 4, 5, 2, 2]     # list for counting
count = {}                         # dictionary for counting
for x in lst:
    count[x] = count.get(x, 0) + 1 # if not  exists, set it to 0
print(count)                       # {2: 3, 4: 2, 5: 2, 3: 1})

So, it is up to you what technique is more suitable for you to use.


Published: 2021-11-25 04:46:25

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.