0

The structure of my dictionary is:

 key             val
 item         a list of values

How I initiated my dict:

dict[item] = [word]
type(dict[item]) ---> gives me list

When going down the loop and try to add more values to the list with the same key, dict[item].append(word) gives me None whereas dict[item] + [word] works

Why is this the case?

  • 1
    Possible duplicate of [Python list + list vs. list.append()](http://stackoverflow.com/questions/5589549/python-list-list-vs-list-append) – Aran-Fey Jul 22 '16 at 14:12
  • By the way `dict[item] + [word]` won't update the actual list inside the dictionary – Tiny Instance Jul 22 '16 at 14:15

2 Answers2

2
  • The code dict[item].append(word) mutates the list at dict[item], and the return value of the function append is None.
  • The code dict[item] + [word] does not mutate the list at dict[item], and just computes a concatenation of two lists.

This is equivalent to:

arr = [1]
res = arr + [2]
assert res == [1, 2]
assert arr == [1]
res = arr.append(2)
assert res is None
assert arr == [1, 2]

For the example from the question to work, the equivalent code to append is:

dict[item] += [word]
Elisha
  • 23,310
  • 6
  • 60
  • 75
0

Using .append()

d = {'example': ['string']}
d['example'].append('test') # mutates the list
print d
>> {'example': ['string','test']}

Using list + list

d = {'example': ['string']}
d['example'] + ['test'] # return {'example':['string', 'test]} but no mutation
print d
>> {'example': ['string']}
m_callens
  • 6,100
  • 8
  • 32
  • 54