-4

So my question is about the line "a, b=b, a+b" as well as the line "a,b = 0,1"

What do these lines mean, what are they doing?

def fib2(n):
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
barker
  • 1,005
  • 18
  • 36

2 Answers2

0

a, b=b, a+b is a multiple assignment statement. In such a statement expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

Similar is the case for a,b=0,1, where a gets 0 and b gets 1.

shiva
  • 2,535
  • 2
  • 18
  • 32
-1
a, b=b, a+b   # is described as

temp = a
a = b
b= temp + b

and if you look at a,b = 0,1 in shell

In [37]: a,b = 0,1

In [38]: a,b
Out[38]: (0, 1)

In [40]: type((a, b))
Out[40]: tuple

In [41]: a
Out[41]: 0

In [42]: b
Out[42]: 1

so it just assignment of variables to the tuple values

Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24