-1

Help me understand difference between list assignment.

I have found that assignment like this

a[0] = b[0]
b[0] = a[0]

Is different from

a[0], b[0] = b[0], a[0]

The values of a and b in both the cases are different , however both of these assignment methods does the same , swapping.

You can run my sample code to see this

    a = [0,1,2]
    b = [3,4,5]
    print "Value of a and b before swaping :"
    print "value of a :" , a
    print "value of b :" , b
    print "\nswap in two line"
    a[0] = b[0]
    b[0] = a[0]
    print "value of a :" , a
    print "value of b :" , b
    print "\nswap in one line"
    # Reinitilizing value of a and b before performing swaping
    a = [0,1,2]
    b = [3,4,5]
    a[0], b[0] = b[0], a[0]
    print "value of a :" , a
    print "value of b :" , b

How are two methods of assignment different? At the first glance they look the same and do the same thing.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137

2 Answers2

1

however both of these assignment methods does the same [thing], swapping.

Not quite... The former example doesn't swap. Instead, it takes the first element of b and puts it in the first element of a. Then it takes the first element of a (which used to be the first element in b) and puts it back into b -- leaving a[0] and b[0] with the same value.

When it's all on the same line, python actually does something a little magical. It effectively creates a new tuple (b[0], a[0]) and then uses that tuple to assign things back into b and a. In other words, it behaves effectively the same as:

temp = (b[0], a[0])
a[0] = temp[0]
b[0] = temp[1]

notice how this is logically different from the first case you had.

mgilson
  • 300,191
  • 65
  • 633
  • 696
0

The difference is the order in which assignment takes place. It has nothing to do with lists however.

The code

 a = b
 b = a

First assigns b to a, then assigns a to b resulting in both having the value that b had before.

On the other side

a, b = b, a

first evaluates b, a. And then take those values and assign to a and b. This results in a proper swap.

skyking
  • 13,817
  • 1
  • 35
  • 57