3

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']
3
  • 1
    Do you understand the difference between [].append('string') and [].append(['string']) ? Commented Nov 15, 2020 at 16:26
  • First one is equivalent to [] + list('string'), second one is equivalent to [] + ['string']) Commented Nov 15, 2020 at 16:29
  • Thank you for your help, @DeepSpace. The list('string') will return ['s', 't', 'r', 'i', 'n', 'g'], however, x = [] x.append('string') x returns ['string']. Commented Nov 15, 2020 at 17:02

2 Answers 2

2

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'.

Sign up to request clarification or add additional context in comments.

2 Comments

How about my second question. The difference between .append and += for ['string']. Thanks.
Just like the same
1
>>> 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.

6 Comments

How about my second question. The difference between .append and += for ['string']. Thanks.
.append('string') is the same as += ['string']
Thank you for your help. I have a further question. Why the list('string') will return ['s', 't', 'r', 'i', 'n', 'g'], however, x = [] x.append('string') x returns ['string']? This question raised from the comment below the question.
Because list('string') views 'string' as a sequence of characters, rather than a single element, just like in case 2 in my answer
Then should I use list(['string'])? Does [] create a list and list command is duplicated here? Thank you for your help.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.