I’m trying to make histogram by python. I am starting with the following snippet:
def histogram(L):
d = {}
for x in L:
if x in d:
d[x] += 1
else:
d[x] = 1
return d
I understand it’s using dictionary function to solve the problem.
But I’m just confused about the 4th line: if x in d:
d is to be constructed, there’s nothing in d yet, so how come if x in d?
The code inside of the
forloop will be executed once for each element inL, withxbeing the value of the current element.Lets look at the simple case where
Lis the list[3, 3]. The first time through the loopdwill be empty,xwill be 3, and3 in dwill be false, sod[3]will be set to 1. The next time through the loopxwill be 3 again, and3 in dwill be true, sod[3]will be incremented by 1.