When you do
lst += ["42"]
You are mutating lst
and appending "42" at the end of it. But when you say,
lst = lst + ["42"]
You are creating a new list with lst
and "42"
and assigning the reference of the new list to lst
. Try this program to understand this better.
lst = ["1"]
print(id(lst))
lst += ["2"]
print(id(lst))
lst = lst + ["3"]
print(id(lst))
The first two ids will be the same, bu the last one will be different. Because, a new list is created and lst
now points to that new list.
Not knowing the difference between these two will create a problem, when you pass a list as a parameter to a function and appending an item to it, inside the function like this
def mutate(myList):
myList = myList + ["2"] # WRONG way of doing the mutation
tList = ["1"]
mutate(tList)
print(tList)
you will still get ['1']
, but if you really want to mutate myList
, you could have done like this
def mutate(myList):
myList += ["2"] # Or using append function
tList = ["1"]
mutate(tList)
print(tList)
will print ['1', '2']