I have a specific problem in which I observe all the confusion of reference and dereference in python. I have a global structure wordhistory which I change on various levels inside a function addWordHistory:
wordhistory = dict()
def addWordHistory(words):
global wordhistory
current = wordhistory
for word in words:
if current is None:
current = {word:[None,1]} #1
else:
if word in current:
current[word][1] += 1
else:
current[word] = [None,1]
current = current[word][0] #2
In line #1, I want to change the value behind the reference that has been assigned to the local variable current in line #2. This does not seem to work like this. Instead, I suspect that only the local variable is changed from a reference to a dictionary.
The below variant works, but I want to save the memory of all the empty leave dictionaries:
wordhistory = dict()
def addWordHistory(words):
global wordhistory
current = wordhistory
for word in words:
if word in current:
current[word][1] += 1
else:
current[word] = [dict(),1]
current = current[word][0]
#1never run. Also you can usecollections.Counterto count the word occurrence in your list of words.#1runs, I have checked it. 2) it is a bit more complicated than that.#2is correct?#1could run, is if current isNone. Current is the same aswordhistory. So the only way for that line to run, would be if you set wordhistory to None, which would make no sense. If it runs, you're doing something more than this code shows.