Lists as values in a dictionary Python
Question: 
    ddic = {'a': 10,'b': 23,'c': [0, 1, 2]}
    n2 = ddic['c']
    n2[-2] = 1000.
    
    ddic
    {'a': 10, 'b': 23, 'c': [0, 1000.0, 2]}
    

Why changing the list at which n2 is pointing, changes also the list of dict
ddic, which is contained into the hash table that ddic defines?

It looks like that when you define a dict, the key-value pairs pops-in the
global namespace and is not contained into the namespace defined by the hash-
table structure.

Someone knows the detailed reason of this?


Answer: Few prenotes

  * Dict keys are immutable whereas values are mutable.
  * When you use `=`, the new variable just references the old list

The value at key `c` is a list. It is pointed to by the key at that place. On
copying to a variable, the reference is passed. This can be confirmed by using
`id`.

    
    
    >>> id(ddic['c'])
    140726603094424
    >>> id(n2)
    140726603094424
    

As you see both the variables are pointing to the same element in memory.
Hence any changes you make in one are reflected to the original one also.

To have a shallow copy of the list you can use `[:]` [as mentioned by
Blckknght](http://stackoverflow.com/questions/29376270/lists-as-values-in-a-
dictionary-pyython/29376334?noredirect=1#comment46933296_29376334)

    
    
    >>> n2 = ddic['c'][:]
    

In python3, you can use (as mentioned by
[Padraic](http://stackoverflow.com/questions/29376270/lists-as-values-in-a-
dictionary-pyython/29376334?noredirect=1#comment46933664_29376334))

    
    
    >>> n2 = ddic['c'].copy()
    

Using `copy` module, you can prevent this from happening as in

    
    
    >>> import copy
    >>> n2 = copy.copy(ddic['c'])
    >>> id(ddic['c'])
    140726603094424
    >>> id(n2)
    140726603177640
    

Reference

  * [`id`](https://docs.python.org/2/library/functions.html#id)
  * [`copy`](https://docs.python.org/2/library/copy.html)

Also note that as mentioned by
[Kasra](http://stackoverflow.com/questions/29376270/lists-as-values-in-a-
dictionary-pyython/29376334?noredirect=1#comment46933178_29376334) in the
comments, dicts don't have as separate space for them as they are data
structures. You can find refernce in
[this](http://svn.python.org/view/python/trunk/Objects/dictobject.c?view=markup)
document

