temp1 object exist only once.
temp1 variable is a reference to that object.
In temp.append(temp1) you add the reference as item to the list, so finally
you have list with 3 items: 3 references to the same object.
Now, when you change*) the object, it changes, and all variables
referencing it, wil
Got it
My confusion was why the three equal elements
Now i see it clearly
If i add the temp1 3 times to temp, when i change it for the last time
inside the loop it changes all the 3 elements inside the full list temp.
Thank you
2015-04-01 14:21 GMT+01:00 Anthony :
> In the first example, you
In the first example, you have only a single dictionary (created outside
the loop). You then append that single dictionary to a list multiple times.
Each item in the list is still just that single dictionary (you are not
creating separate copies of the dictionary). In the first loop, you are
se
Python is treating the dictionary as a pure object where the reference is
maintained and whatever changes you do (other than redefining it) results
in the same changes reflected in all the places where the object occurs.
In the first set of code, you are not redefining the dictionary (temp1) and
The 2nd example is bullet proof.
However the 1st example should work also because if i print temp1 before
append temp1 to the temp var i see it like
{'a': 0, 'c': 0, 'b': 0}
{'a': 1, 'c': 1, 'b': 1}
{'a': 2, 'c': 2, 'b': 2}
temp=[]
temp1={'a':0,'b':0,'c':0}
for x in range(3):
temp1['a']=x
The difference is that in the second example you're creating the dictionary
inside the loop. In the first example you create the dictionary outside so
each step of the loop is modifying the same dictionary and then you put
that same dictionary 3 times in the list.
--
Resources:
- http://web2py
6 matches
Mail list logo