Please explain this Python code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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']

26th Feb 2021, 6:30 AM
Silent
9 Answers
+ 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')
26th Feb 2021, 6:51 AM
G B
G B - avatar
+ 3
Use two characters d and e separately
27th Feb 2021, 10:31 AM
Ahmed Mohammed Alnor Abdalmahmod Abdalslam
Ahmed Mohammed Alnor Abdalmahmod Abdalslam - avatar
+ 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')
27th Feb 2021, 10:56 AM
Théophile
Théophile - avatar
+ 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 .
27th Feb 2021, 8:48 PM
Zovelosoa Jph
Zovelosoa Jph - avatar
+ 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.
28th Feb 2021, 12:06 AM
Oleksandr Lytvynov
Oleksandr Lytvynov - avatar
+ 1
Ok
26th Feb 2021, 7:13 AM
Silent
+ 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]
27th Feb 2021, 2:53 PM
Thamsanqa Sthloe
Thamsanqa Sthloe - avatar
0
Following up on what G B said, you will get your expected result with list = ['a', 'b', 'c'] list += ['de'] print (list)
28th Feb 2021, 2:00 AM
David Ashton
David Ashton - avatar
- 3
list += 'de' Is equivalent to : list.extend('de')
26th Feb 2021, 7:57 AM
Théophile
Théophile - avatar