I've noticed when experimenting with lists that p= p+i
is different then p += i
For example:
test = [0, 1, 2, 3,]
p = test
test1 = [8]
p = p + test1
print test
In the above code test
prints out to the original value of [0, 1, 2, 3,]
But if I switch p = p + test1
with p += test1
As in the following
test = [0, 1, 2, 3,]
p = test
test1 = [8]
p += test1
print test
test
now equals [0, 1, 2, 3, 8]
What is the reason for the different value?
p = p + test1
assigns a new value to variable p
, while p += test1
extends the list stored in variable p
. And since the list in p
is the same list as in test
, appending to p
also appends to test
, while assigning a new value to the variable p
does not change the value assigned to test
in any way.
tobias_k explained it already.
In short, using + instead of += changes the object directly and not the reference that's pointing towards it.
To quote it from the answer linked above:
When doing foo += something you're modifying the list foo in place, thus you don't change the reference that the name foo points to, but you're changing the list object directly. With foo = foo + something, you're actually creating a new list.
Here is an example where this happens:
>>> alist = [1,2]
>>> id(alist)
4498187832
>>> alist.append(3)
>>> id(alist)
4498187832
>>> alist += [4]
>>> id(alist)
4498187832
>>> alist = alist + [5]
>>> id(alist)
4498295984
In your case, test got changed since p was a reference to test.
>>> test = [1,2,3,4,]
>>> p = test
>>> id(test)
4498187832
>>> id(p)
4498187832
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With