9

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?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
Manny_G
  • 333
  • 3
  • 11
  • 2
    Here is an in depth answer to this: http://stackoverflow.com/questions/2347265/what-does-plus-equals-do-in-python – Jason Sperske Dec 19 '13 at 21:29
  • See also http://stackoverflow.com/a/4773111/2314737 and http://stackoverflow.com/a/2027311/2314737 – user2314737 Dec 19 '13 at 21:52
  • See also [Combining elements in list: seems like python treats the same item in two different ways and I don't know why](http://stackoverflow.com/q/17240162) and [When is "i += x" different from "i = i + x" in Python?](http://stackoverflow.com/q/15376509) – Martijn Pieters Dec 19 '13 at 21:54

3 Answers3

11

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
  • 81,265
  • 12
  • 120
  • 179
1

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
Community
  • 1
  • 1
Bharadwaj Srigiriraju
  • 2,196
  • 4
  • 25
  • 45
1

+ and += represent two different operators, respectively add and iadd

From http://docs.python.org/2/reference/datamodel.html#object.iadd: the methods iadd(self,other), etc

These methods are called to implement the augmented arithmetic assignments (+=, -=, =, /=, //=, %=, *=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result

p += test1 uses the iadd operator and hence changes the value of p while p = p + test1 uses the add which does not modify any of the two operands.

user2314737
  • 27,088
  • 20
  • 102
  • 114