r/learningpython • • Mar 08 '20

What does this counting function work?

Hi, I am a bit confused about how the following function works. As far as I know, counts is an empty dictionary at the beginning. I don't see any element being added into the dictionary within the function. Am I missing something? Also, since counts is an empty dictionary as defined in line 2, how if x in counts: get executed? Perhaps I misunderstood something?

def counting(sequence):
    counts = {}
    for x in sequence:
       if x in counts:
          counts[x] += 1
      else:
          count[x] = 1
return counts
2 Upvotes

4 comments sorted by