1 1. L = []2 for in xrange:3 3. L.append ({' num ': i})4print l
1 1. L = []2 2. A = {' num ': 0}3 for in Xrange ():4 4. a[' num '] = i5 5. L.append (a)6print l
Are the two sections of code running the same, if not the same, what are the reasons?
The result of the above code:
1 1. [{' num ': 0},{' num ': 1},{' num ': 2},{' num ': 3},{' num ': 4},{' num ': 5},{' num ': 6},{' num ': 7},{' num ': 8},2 {' num ': 9}]
The result of the code below:
1 1. [{' num ': 9},{' num ': 9},{' num ': 9},{' num ': 9},{' num ': 9},{' num ': 9},{' num ': 9},{' num ': 9},{' num ': 9},2 {' num ': 9}]
So here's the reason:
The reason is that the dictionary is a mutable object, and in the operation of L.append (a) below, the reference to dictionary A is passed to the list L, when
Continue to modify the value of a[' num '), the value in L will also change, equivalent to a shallow copy.
Consider the following Python code, if the run ends, what is the result of the run on the command line?