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']
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'.
>>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With