1

I have a strange problem with list.append(). I build a list joining some values from a dict, as follows:

In [3]: myDict = {'k1': u'value1', 'k2': [u'value2']}

In [4]: myList = myDict['k2']

In [5]: myList
Out[5]: [u'value2']

In [6]: myList.append(myDict['k1'])

In [7]: myList
Out[7]: [u'value2', u'value1']

In [8]: myDict 
Out[8]: {'k1': u'value1', 'k2': [u'value2', u'value1']}

I don't understand the reason why myDict is modified after append in In [6] (see the difference between In [2] and Out [8]).

floatingpurr
  • 7,749
  • 9
  • 46
  • 106
  • 2
    Because they refer to the same object. – Daniel Roseman Oct 23 '15 at 11:24
  • 1
    Becuase myDict and myDict['k2'] _refer to the same list_. – RemcoGerlich Oct 23 '15 at 11:25
  • 1
    `myList is myDict['k2']` - a better question might be *why did you expect something else to happen?* – jonrsharpe Oct 23 '15 at 11:26
  • 3
    Assignment statements in Python do not copy objects, they create bindings between a target and an object. – Doon Oct 23 '15 at 11:26
  • @Doon beautiful explanation should copy this for future use :) – The6thSense Oct 23 '15 at 11:28
  • 1
    @VigneshKalai Stolen from copy in the stdlib :) – Doon Oct 23 '15 at 11:31
  • 1
    You may find this article helpful: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), which was written by SO veteran Ned Batchelder. – PM 2Ring Oct 23 '15 at 11:36
  • 1
    this really boils down to "pass by reference" concept (not just in python but in many other languages)...see my answer in this post http://stackoverflow.com/questions/33222944/append-vs-redefining-variable-in-python/33223855#33223855 – labheshr Oct 23 '15 at 11:40

2 Answers2

3

Because when you assign myDict['k2'] to myList you are actually just creating a pointer, myList, to the value with key k2 in myDict. You need to create a copy of myDict['k2'] otherwise you are just modifying the original.

Try myList = list(myDict['k2']).

Gilbert Allen
  • 343
  • 2
  • 13
2

myDict[k2] is a pointer to a list object. You then set myList to point to the same list object. when you modify the list, all of the pointers that point to it see the modified one.

The6thSense
  • 8,103
  • 8
  • 31
  • 65
Paul Becotte
  • 9,767
  • 3
  • 34
  • 42