Please explain this Python code | SoloLearn: Learn to code for FREE!

+7

Please explain this Python code

list = ['a', 'b', 'c'] list += 'de' print (list) The output is ['a', 'b', 'c', 'd', 'e'] Why Not?🤔 ['a', 'b', 'c', 'de']

2/26/2021 6:30:57 AM

Silent

9 Answers

New Answer

+17

'+' Operator applied to list objects is used to concatenate lists. When you concatenate a list obj with a str objects, the str objects will get internally converted to list, which results in list(de) # ['d', 'e']. Thats why your code is behaving so. You will get your expected result, when you use list.append('de')

+3

Use two characters d and e separately

+2

I realized that I have got 3 dislikes on my answer. That is weird. Maybe I have to explain a little bit more... I said that list += 'de' is equivalent to : list.extend('de') This is not *totally* right list += 'de' Is in fact equivalent to : list = list.__iadd__('de') (of course, if we don't look further at the bytecode, because we can see that it is not *strictly* equivalent) And here is a probable implementation of __iadd__ on lists: def __iadd__(self, obj): self.extend(obj) return self So it is *quite* equivalent to: list.extend('de')

+2

You should make another list = ['de'] and add it to your list to get the second result Python convert str char to individual element list. So the reason .

+2

If you add a string to the list, Python will add each letter separately in the list. If you like to add the whole word, you have to use "append" method to do this.

+1

+1

they are srtings so they are indexed that why they have there own indexs you should append de if you want your output to be [a,b,c,de]

0

Following up on what G B said, you will get your expected result with list = ['a', 'b', 'c'] list += ['de'] print (list)

-3

list += 'de' Is equivalent to : list.extend('de')