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 
hence all three members of the temp end up referring to the temp1 at the 
end. In the second case, you are redefining the temp1.

Look at the meaning of shallow copy and deep 
copy https://docs.python.org/2/library/copy.html in Python. Also there are 
similar questions in Stackoverflow. 
e.g.http://stackoverflow.com/questions/5244810/python-appending-a-dictionary-to-a-list-i-see-a-pointer-like-behavior

In your first example, may be you can append a new dictionary with values 
from temp1: that is temp.append({'a':temp1['a'].....})

Good luck.

Sundar
-------------------------

On Wednesday, April 1, 2015 at 5:03:01 PM UTC+5:30, Ramos wrote:
>
> Please explain why this code
>
> temp=[]
> temp1={'a':0,'b':0,'c':0}
> for x in range(3):
>     temp1['a']=x
>     temp1['b']=x
>     temp1['c']=x
>     temp.append(temp1)
> print temp
>
>
> prints
>
> [{'a': 2, 'c': 2, 'b': 2}, {'a': 2, 'c': 2, 'b': 2}, {'a': 2, 'c': 2, 'b': 
> 2}]
>
> instead of 
>
> [{'a': 0, 'c': 0, 'b': 0}, {'a': 1, 'c': 1, 'b': 1}, {'a': 2, 'c': 2, 'b': 
> 2}]
>
> i always did it like this
>
> temp=[]
>
> for x in range(3):
>     *temp1={'a':0,'b':0,'c':0}*
>     temp1['a']=x
>     temp1['b']=x
>     temp1['c']=x
>     temp.append(temp1)
> print temp
>
> this prints it correctly but dont understand the diference
>
>
> Thank you
> António
>

-- 
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
--- 
You received this message because you are subscribed to the Google Groups 
"web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to