Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does adding to a list do different things? [duplicate]

Tags:

python

list

>>> 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?

like image 416
kkSlider Avatar asked Apr 13 '12 23:04

kkSlider


Video Answer


1 Answers

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.

like image 121
Ignacio Vazquez-Abrams Avatar answered Oct 11 '22 15:10

Ignacio Vazquez-Abrams