13
>>> aList = []
>>> aList += 'chicken'
>>> aList
['c', 'h', 'i', 'c', 'k', 'e', 'n']
>>> aList = aList + 'hello'


Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    aList = aList + 'hello'
TypeError: can only concatenate list (not "str") to list

I don't get why doing a list += (something) and list = list + (something) does different things. Also, why does += split the string up into characters to be inserted into the list?

Usagi
  • 2,896
  • 2
  • 28
  • 38
kkSlider
  • 595
  • 1
  • 8
  • 17

3 Answers3

5

list.__iadd__() can take any iterable; it iterates over it and adds each element to the list, which results in splitting a string into individual letters. list.__add__() can only take a list.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
5

aList += 'chicken' is python shorthand for aList.extend('chicken'). The difference between a += b and a = a + b is that python tries to call iadd with += before calling add. This means that alist += foo will work for any iterable foo.

>>> a = []
>>> a += 'asf'
>>> a
['a', 's', 'f']
>>> a += (1, 2)
>>> a
['a', 's', 'f', 1, 2]
>>> d = {3:4}
>>> a += d
>>> a
['a', 's', 'f', 1, 2, 3]
>>> a = a + d
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: can only concatenate list (not "dict") to list
Nolen Royalty
  • 18,415
  • 4
  • 40
  • 50
1

To solve your problem you need to be adding lists to lists, not strings to lists.

Try this:

a = []
a += ["chicken"]
a += ["dog"]
a = a + ["cat"]

Note they all work as expected.

yamen
  • 15,390
  • 3
  • 42
  • 52