Difference between list += ‘string’ and list +=[‘string’]

Viewed 208

I have a question about the difference between list += ‘string’ and list +=[‘string’]. I mistook input a command in Python as:

Completedlist = []
Completedlist += ‘bob’

Which will return:

['b', 'o', 'b']

I am not quite sure about why this happens. Besides, is there any difference between += and append in this scenario? I mean between completedlist.append(‘bob’) and completedlist += [‘bob’]. Thank you in advance for your help.

2 Answers

The reason is documented, see here

+= just behaves like .extend() for a list, which appends contents of a list to the list. So, if you += string then it takes the string like list and append each characters, but in the other case it adds the content of the list, which is the string I mean bob itself

>>> a = list('dog')
>>> a += 'food'
>>> a
['d', 'o', 'g', 'f', 'o', 'o', 'd']

>>> a = list('dog')
>>> a += ['food']
>>> a
['d', 'o', 'g', 'food']

+= ['food'] treats the whole string 'food' as a single list as a single element to be added to the list

+= 'food' treats the string 'food' as a list of characters to be added as elements to the list one-by-one

What might be a bit confusing here is that there are no separate data types for strings and characters in Python. A string is a list of 1-letter strings essentially.

Related