0

I'm trying to understand what is happening in this block of code

def enum(seq):
    n = 0
    for i in seq:
        yield n, i
        n += 1
def fibonacci():
    i = j = 1
    while True:
        r, i, j = i, j, i + j
        yield r

I have a general understanding of how generators work, I'm just confuse about the line:

r, i, j = i, j, i +j

and what is happening on it. Thanks.

Taku
  • 31,927
  • 11
  • 74
  • 85
tittimous
  • 39
  • 4
  • Possible Dupe? http://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python – mgilson Jun 27 '16 at 16:27
  • Standard tuple assignment and unpacking, which in Python3 has become much more powerful: https://www.python.org/dev/peps/pep-3132/ – AChampion Jun 27 '16 at 16:38

3 Answers3

0

It is called 'tuple assignment'.

Often, you encounter multiple assignments like

a = 1
b = 2
c = 3

This can be rewritten as:

(a, b, c) = (1, 2, 3)

Or even like this:

a, b, c = 1, 2, 3

If you want to swap values:

a, b = b, a

Yes, that also works.

In your case, some swapping and some addition is happening simultaneously*. r is the value that will be returned, i is the value to be returned on the next step, j - to be returned afterwards. And what would be returned after j? i + j and so on.

Daerdemandt
  • 2,281
  • 18
  • 19
0

This is a standard "unpacking assignment" - the three values on the right hand side are computed, then the values are bound to the locations (in this case they are all simple names, but they could in theory be container elements) on the left hand side. This particular case is broadly equivalent to

r = i
i = j
j = i+j

Note, though, that in the general case it's possible to do things in a single statement that you couldn't otherwise do safely without using temporary variables. The classical "exchange two variables" required a temporary, as in

tmp = i
i = j
j = tmp

but in python you can just use

i, j = j, i

and everything will Just Work (tm).

holdenweb
  • 33,305
  • 7
  • 57
  • 77
0

The line

r, i, j = i, j, i+j

is a sequence unpacking statement.

Let i = j = 1.

  1. First the right hand side i, j, i+j is evaluated and packed into a tuple (1, 1, 2).
  2. Then the tuple is unpacked into the names r, i, and j such that r = 1, i = 1, and j = 2.

This is briefly mentioned at the end of section 5.3 in the python docs.

eistaa
  • 86
  • 1
  • 7