0

I am pretty confused with the difference in results of the Python codes below. Why in first case "a" does not change upon the change of "b", but in second one does?

a=b=[]
b = [1,2,3]
print b,a
########## compare with below ################################
a=b=[]
b.append([1,2,3])
print b,a

Result of first part is: [1,2,3] [ ] and result of the second part is: [[1,2,3]] [[1,2,3]]

It was suggested that it is a duplicate question but I think here I am changing the list "b" with two different ways and I guess it could show how these two methods of variable manipulation could be different.

Amin
  • 261
  • 3
  • 16
  • 1
    In the first part you are pointing b at a new, different list. In the 2nd a and b both point to the same list. – jeff carey Nov 03 '15 at 07:28

3 Answers3

2

Because = is not the same as append.

When you do b = [1, 2, 3], you assign a new value to b. This does not involve the old value of b in any way; you can do this no matter what value b held before.

When you do b.append(...), you modify the object that is the existing value of b. If that object is also the value of other names (in this case, a), then those names will also "see" the change. Note that, unlike assignment, these types of operations depend on what kind of value you have. You can do b.append(...) because b is a list. If b was, say, an integer, you could not do b.append, but you could still do b = [1, 2, 3].

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
2

In the first example, you are reassigning the variable b, and now it points to another list.

a = b = [] # a -> [] <- b
b = [1, 2, 3] # a -> [], b -> [1, 2, 3]

In the second example, both a and b variables are pointing to the same list, and you are inserting values in the list:

a = b = [] # a -> [] <- b
b.append([1, 2, 3]) # a -> [[1, 2, 3]] <- b
awesoon
  • 32,469
  • 11
  • 74
  • 99
1

To elaborate on the other answers, this is straight from the Python docs:

list.append(x)
    Add an item to the end of the list; equivalent to a[len(a):] = [x].

Looking at:

a[len(a):] = [x]

it is easy to see that using append is modifying the original list (a in the python sample code, b in your case).

As the others people have pointed out, using an assignment statement is assigning a new value to b, instead of modifying it via append.

Tyler
  • 17,669
  • 10
  • 51
  • 89