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?

3

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.