Follow the UnboundLocalError Cause of the unintuitive behavior (suppose you read it). Consider the following Python script:
def f():
The result of the script is:
1 b ['cc', 'c', 'c'] {'dd': 6, 'd': 5, 'ddd': 7} set(['e'])
The recorded lines (marked as 1,2) are the lines that will be associated with the UnboundLocalError, and the SO question I refer to explains why. However, line marked 3 works!
By default, lists are copied by reference in Python, so itβs clear that c changes when cc changes. But why does Python allow c to change, first of all, if it does not allow changing a and b directly from the method area?
I donβt see how the fact that by default lists are copied by reference in Python should make this constructive solution inconsistent.
What am I missing people?
UPDATE:
- For completeness, I also added a dictionary equivalent to the above question, i.e. added source code and marked update
# Update - For added completeness, I also added a set of equivalents. The complex behavior is actually amazing to me. I expected it to act like a list and a dictionary ...
source share