Why list concatenation with string behaves differently for below scenarios in python: | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Why list concatenation with string behaves differently for below scenarios in python:

l=[] l=l+'hi' # error l+='hi # output ['h','i']

19th Aug 2018, 2:25 PM
Deepak Jayaprakash
Deepak Jayaprakash - avatar
3 Answers
+ 3
There are several ways to add elements to a list. ''' l=[] l=l+['hi'] # adding a list to a list print(l) l[0]='Hello' # adding 'Hello' to the 0 index print(l) l=[] l+='hi' # the += operator is iterative for lists print(l) l.append('hello') # adds an element to the end of the list print(l) l.insert(1, 'hey') # adds an element to a specific index print(l) l='string' l=l+'hi' print(l) l='abc' l+='hi' print(l) ''' Therefore the same means of manipulating strings and integers cannot be applied to lists, not directly. If properly sliced or elements extracted from within a list can be manipulated in this manner because they were explicitly removed from the list. If "l" was a string, this would not be an issue, but you are trying to compare "apples" and "oranges".
19th Aug 2018, 6:11 PM
Steven M
Steven M - avatar
+ 1
You need a deeper understanding of pythons' memory allocation works, as a beginner i really struggled with such issues. In your scenario: Think it this way I = [] (is an empty bag of apples) and 'hi' (single apples). [] + 'hi' mean physically your concatenating a bag and an apple. [] += 'hi' mean physically your adding apples inside the bag. So, a list is of 'type' container and a string is of 'type' characters.
21st Aug 2018, 9:30 AM
Pheega
+ 1
yeah, py idiomatics not to say damned
21st Aug 2018, 10:34 PM
Арсений Чеботарёв
Арсений Чеботарёв - avatar