[Tutor] Fibonacci Series

Alan Gauld alan.gauld at btinternet.com
Sun Nov 24 16:48:03 CET 2013


On 24/11/13 13:05, Rafael Knuth wrote:

> "a" and "b" on the left side are unchangable tuples and they simply get
> unpacked on the right side.

Be careful about terminology here. a,b is a single tuple with two 
values. But a and b are variables not tuples.

Tuples are collections of (one or more) values. In python they are 
separated by commas. Thus a single valued tuple looks like

(5,)

A double valued tuple like

(3,4)

And so on.
Note the parentheses are optional and only needed for
disambiguating the tuple. 3,4 is also a double valued
tuple.

Variables are names that refer to values. A value can
be any Python object (including a tuple!). So

a = None
a = 5
a = 's'
a = (1,2)

are all valid values for the variable 'a'

And

t = ( (1,2), (2,3) )

is a single tuple composed of two other tuples.

So

a,b = 3,4

is assigning the tuple on the right side to
the tuple on the left. It *simultaneously*
assigns 3 to a and 4 to b.

It doesn't matter what a and b were storing previously
it creates a new tuple on the right and assigns it to
another newly created one on the left. Note that the
right side could be an existing tuple but the one
on the left is always a new tuple. Thus

a,b = t  # see above

would only create one new tuple (on the left) and a
would have the value t[0], or (1,2) and b would be
t[1] or (2,3).

The final thing that makes your case complicated is
that a,b appear on both sides of the assignment. But
if you remember that the assignments are effectively
happening simultaneously it all follows the same rules.

Tuple assignment/unpacking is a powerful technique in Python.
Without it we would need to introduce extra variables so that

a,b = b, a+b

would become

old_a = a
a = b
b = old_a + b

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list