-1

I am testing a python script, where I have to constantly store the old values of 2 variables and then return them through a function. For this I took fibonacci series as an example:

def fibonacci(n):
  a=0;b=1;cnt=0;
  while True:
    if (cnt > n):
      return;
    yield a;
    c=b;b=a+b;a=c;
    cnt +=1;

fib=fibonacci(5)
for x in fib:
  print(x,end=" ")

Everything works perfectly as expected here, and the output is also as expected. I however tried to write it in a different way, where instead of using an extra variable "c", I can still do the swap of old values efficiently, and I practically bumped on this (though have no idea how the assignment is working here) :

Instead of the line:

c=b;b=a+b;a=c;

Used:

a,b=b,a+b

So a detailed explanation will be appreciated.

dig_123
  • 2,240
  • 6
  • 35
  • 59
  • 1
    don't put commands in one line `c=b;b=a+b;a=c;` it makes code unreadable for people. – furas Jan 04 '17 at 07:21
  • 1
    This is possible because python supports [unpacking](https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch01s01.html) –  Jan 04 '17 at 07:22
  • 1
    comma `,` is used to create `tuple` - so you "pack" values into tuple `b,a+b` and later you "unpack" this tuple to variables `a,b` – furas Jan 04 '17 at 07:24
  • 1
    IOW, `a, b = b, a + b` is the same as `(a, b) = (b, a + b)` – PM 2Ring Jan 04 '17 at 07:24
  • 1
    The feature is also known as simultaneous assignment: `a` becomes `b` and at the same time `b` becomes `a+b`. – DYZ Jan 04 '17 at 07:25

1 Answers1

2

It is a feature of Python.

>> a=1  
>> b=2  
>> a, b = b, a  
>> a, b   
>> (2, 1)

The right side of the assignment is an expression that creates a new tuple. The other side of the assignment immediately unpacks that (unreferenced) tuple to the names a and b.

After the assignment, the new tuple is unreferenced and marked for garbage collection, and the values bound to a and b have been swapped.

check this tuple and sequences

Hope this helps.

McGrady
  • 10,869
  • 13
  • 47
  • 69