I want to know how += operator is working?
the in-place assignment +=
operator works in 2 ways (from the docs):
1)For immutable objects
For immutable targets such as strings, numbers, and tuples, the
updated value is computed, but not assigned back to the input variable
this means that you will create a new object each time +=
is used (if your object is immutable)
2)For mutable objects
For mutable targets such as lists and dictionaries, the in-place
method will perform the update, so no subsequent assignment is
necessary
this means that you will not create a new object each time +=
is used (if your object is mutable)
In your example, to use li+=i
you have to make sure that i
is a list, otherwise will not work
Here:
li = []
for i in 'string':
li = li + [i]
you are concatenating 2 lists but each time you are creating a new list li
, you can check by using the built-in funtion id:
li=[]
for i in '1':
print(id(li))
li=li+[i]
print(id(li))
output:
140661631713104
140661644452240
you could use the in-place assignment +=
operator like this:
li=[]
for i in '1':
print(id(li))
li += [i]
print(id(li))
output:
140661641698592
140661641698592
as you can see the elements are appended to the li
list without creating a new li
list which is more efficient, this works identically like list.extend
to add another element to your list, not using a list, you can use list.append