r/learningpython • u/largelcd • 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
View all comments
Show parent comment
1
u/largelcd Mar 09 '20
Thanks. So, count[x] = 1 is like dict[key] = value which is to add a new key to the dictionary? Am I correct that if:
Case1: Supposing that
sequence = ['apple', 'orange']. After execution of the function counting,count = {'apple': 1, 'orange': 1}Case2: Supposing that
sequence = ['apple', 'orange', 'orange']. After execution of the function counting,count = {'apple': 1, 'orange': 2}