[Tutor] Understanding code line
spir
denis.spir at gmail.com
Sat Mar 22 14:45:46 CET 2014
On 03/21/2014 06:14 PM, Gary wrote:
>
> Pythonists
>
> I am trying to understand the difference between
>
> a = b
> b = a + b
> and
>
> a,b = b, a+ b
> When used in my Fibonacci code the former generates 0,1,2,4,8,16,32 and the later
> Generates 0,1,1,2,3,5,8,13,21,34,55,89. The second is the sequence I want, but I would
> Like to understand the second code sequence better so I can write the code in R and Scilab as well as python.
To understand
a, b = b, a+ b
correctly, think of it operating in parallel, each assignment independantly. So,
it does what you think (and need to compute a fibonacci sequence).
A better explanation, maybe, is that python has *tuples*, which are groups of
values held together; and are better written inside parens (), like (1,2,3) or
(x,y,z). But () are not compulsary, a comma is enough to make a tuple. Here we
have two 2-tuples, also called pairs, meaning tuples of 2 values. The assignment
thus actually means:
(a, b) = (b, a+b)
So, python *first* constructs the right side tuple, *then* assigns it to the
left side; however, since we don't have on the left side a (named) tuple
variable, it actually assigns to the local variables a & b, in //. Hope it's
clear. You can consider this last step as nice, little magic. Rarely needed, but
very handy when needed.
d
More information about the Tutor
mailing list