Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between adding lists in python with + and += [duplicate]

Tags:

python

list

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?

like image 872
Manny_G Avatar asked Dec 19 '13 21:12

Manny_G


2 Answers

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.

like image 194
tobias_k Avatar answered Sep 21 '22 09:09

tobias_k


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
like image 42
Bharadwaj Srigiriraju Avatar answered Sep 22 '22 09:09

Bharadwaj Srigiriraju