Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between list += 'string' and list += ['string']

I mistakenly input a command in Python as:

completed_list = []
completed_list += 'bob'

Which returns:

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

Why does this happen?

Besides, is there any difference between += and append in this scenario? I mean between these:

completed_list.append('bob')
completed_list += ['bob']
like image 615
Qiang Super Avatar asked Nov 20 '25 20:11

Qiang Super


2 Answers

The reason is documented, see Mutable Sequence Types

+= behaves like .extend() for a list, which adds the contents of an iterable to the list. So, if you += string then it takes the string and appends each character, i.e. 'b', 'o', 'b', but if you += [string] then it adds the contents of the list, which is the string itself, i.e. 'bob'.

like image 150
programmer365 Avatar answered Nov 22 '25 08:11

programmer365


>>> 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 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 in some contexts treated as a list of 1-letter strings.

like image 42
xjcl Avatar answered Nov 22 '25 10:11

xjcl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!