0

Could anyone help to explain, why the values in dictionary change when using 'append'.

dic1 = {1:[[1],[2]]}
for x in dic1.keys():
    for tt in dic1[x]:
        print tt
        tt = tt + [1]
        print tt
dic1

output:

[1]
[1, 1]
[2]
[2, 1]
Out[67]:
{1: [[1], [2]]}

However

dic1 = {1:[[1],[2]]}
for x in dic1.keys():
    for tt in dic1[x]:
        print tt
        tt.append("s")
        print tt
dic1

output - if use append instead of plus, dic1 changed

[1]
[1, 's']
[2]
[2, 's']
Out[68]:
{1: [[1, 's'], [2, 's']]}
  • 1
    Sounds like you could use a quick guide to the difference between variables and objects: https://nedbatchelder.com/text/names.html – user2357112 Feb 27 '18 at 17:48
  • Because it will create a new list when you do `tt = tt + [1]` because of which no value is changes but with append you update the list – Shashank Feb 27 '18 at 17:51

3 Answers3

1

This is because tt in tt = tt + [1] is a local name, not the one inside dic1. Thus you changed the valued of this local name, not the value inside the dic1.

If you want to modify the object itself like in your first solution, use tt[:]:

dic1 = {1:[[1],[2]]}
for x in dic1.keys():
    for tt in dic1[x]:
        print tt
        tt[:] = tt + [1]
        print tt
llllllllll
  • 16,169
  • 4
  • 31
  • 54
  • Thank you @liliscent. another question, "[:] is the array slice syntax for every element in the array." still don't understand that why [:] helps to change the value inside dic1. – karlhuggle Mar 07 '18 at 11:03
  • found the explanation from here: https://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice :) – karlhuggle Mar 12 '18 at 16:51
0

This happens because lists are mutable and append changes the object itself instead of creating a new one.

In the first case the + actually creates a new object, so the original tt in the dictionary is not altered.

However in the second case, append does modify the actual dictionary's tt

ted
  • 13,596
  • 9
  • 65
  • 107
0

Append treats the list as mutable, whereas addition does not.

list = [1,2,3]
print(id(list))
list.append(1)
print(id(list))
list = list + [1]
print(id(list))

In other words append does not create a new object in memory, it just modifys the object that's already there, whereas addition creates an entirely new object. In the context of the dictionary, this means the values within it are changed when using append.

RandomBob
  • 106
  • 1