Note: This was part of a much larger, more complex piece of code where this single line of code made sense given the context. I know I can simply write 1 in the list.
The code I am referring to is from another question here: How to implement an efficient bidirectional hash table?
Anyway, what I don't understand is why the return value, a list, can be appended to, and why that change in reflected within the list contained inside the dictionary. As far as I knew, the returned value was a somewhat copy of the list, not the same list itself in the dictionary:
>>> dict = {}
>>> dict.setdefault("a",[]).append(1)
>>> print(dict)
>>> {"a": [1]}
At first, I thought this was because the list returned is only returned after the execution of the line, which seemed to make a lot of sense, so to test this I assigned the result of dict.setdefault("a", []) to a variable:
>>> dict = {}
>>> l = dict.setdefault("a",[])
>>> l.append(1)
>>> print(l)
>>> [1]
>>> print(dict)
>>> {"a": [1]}
What's even stranger, is that appending to the list directly does not work. By directly, I mean this:
>>> dict = {}
>>> dict.setdefault("a",[].append(1))
>>> print(dict)
>>> {"a": None}
So what I would not have expected to be possible is what actually happened (changing a returned value with that change being made to the copy of that value), and what I thought would be possible is not (appending directly to a list).
If anyone knows why this is, and wherein the python documentation I may be able to read up more about this behaviour to further my understanding, that would be greatly appreciated.
Thanks.