+ 5
Why list concatenation with string behaves differently for below scenarios in python:
l=[] l=l+'hi' # error l+='hi # output ['h','i']
3 Respostas
+ 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".
+ 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.
+ 1
yeah, py idiomatics not to say damned