[Tutor] Fibonacci Series

Rafael Knuth rafael.knuth at gmail.com
Mon Nov 25 09:24:27 CET 2013


@Alan
@Dave
@Dominik

thank you all so much for the elaborate explanations! It's really
simple and crystal clear now, the most difficult part was actually to
detect and overcome my own misconceptions. Once I did that, the rest
was really easy. Kind of a valuable learning for the future ;-)
Instead of asking: "What's wrong with this code?" I should ask myself:
"What's wrong with my assumption about this code?" whenever I hit the
wall.

Again, thank you so much & have a great week!

Raf

On Sun, Nov 24, 2013 at 4:48 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> 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
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list