Comma Variable Assignment

Can someone explain to me what line 4 does?

1 def fib2(n):  # return Fibonacci series up to n
2 ...     """Return a list containing the Fibonacci series up to n."""
3...     result = []
4...     a, b = 0, 1  #this line
5...     while a < n:
6...         result.append(a)
7...         a, b = b, a+b
8...     return result    
+4
source share
2 answers

What do you describe the purpose of the tuple :

a, b = 0, 1

equivalent to a = 0and b = 1.

However, it can have interesting effects if, for example, you want to change the values. How:

a,b = b,a

first build a tuple (b,a), and then turn it off and assign it to aand b. This, therefore, is not equivalent:

#not equal to
a = b
b = a

but (using temporary):

t = a
a = b
b = t

In the general case, if you have a list of variables separated by commas to the left of the assignment operator, and the expression that generates the tuple, the tuple is unpacked and stored in the values. So:

t = (1,'a',None)
a,b,c = t

1 a, 'a' b None c. , : , , .. .

+6

, , a b, a= 0 b= 1. , 7 a b b a b.

, . , . python - .

, , , . (a, b) = (0, 1) , python, ( , . .. foo((a, b)) foo, foo(a, b) .)

. a, b, c, d, e = 0, 1, 2, 3, 4, , : ret1, ret2, ret3 = foobar(1)

+1

Source: https://habr.com/ru/post/1666613/


All Articles