Python Forum

Full Version: A simple python doubt
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In the following function,
def fibonaci():
    first = 0
    last = 1
    while True:
        first, last = last, first + last
        yield first
I am having difficulty understanding the first statement inside the while loop:
first, last = last, first + last

What it does ?
How first, last gets the values after each iteration ?
It is a tuple assignment, a way to assign several variables in one statement
>>> first, last = 5, 23
>>> first
5
>>> last
23
You can think of this as packing and unpacking.
first = 1
last = 2

temp = last, first + last  # Pack last and first + last into temporary tuple
print(temp)
first, last = temp  # Unpack temporary tuple into first and last
print(first, last)
Output:
(2, 3) 2 3