Indexing Into A Tuple

Tim Daneliuk tundra at tundraware.com
Wed Jun 27 21:09:07 CEST 2001


Steve Holden wrote:
> 
> "Tim Daneliuk" <tundra at tundraware.com> wrote ...
> > Hmm, it works, but I don't understand why.  I have a tuple of tuples
> > defined as follows:
> >
> > MyTuple = ( ("a", "b"), ("c", "d")...)
> >
> > Now, I want to iterate across it to print the pairs.  This works as I
> > would expect:
> >
> > for x in MyTuple:
> >         print x[0], x[1]
> >
> This says "take each value from MyTuple, assign it to x, and run the loop
> body".
> 
> > But so does this:
> >
> > for x, y in MyTuple:
> >         print x, y
> >
> This says "take each value from MyTuple, assign its first element to x and
> its second element to y (and there'd better not be any other elements if you
> don't want an exception), and run the loop body".
> 
> > Intuitively (and, obviously, incorrectly) it seems to me that the 1st
> > time through, the second example should return:
> >
> >       x=("a", "b") and y=("c", "d")
> >
> > Instead, it returns x="a", and y="b" just like the first example.
> >
> > Why?
> > --
> Basically, because it's mirroring Python's standard binding behavior:
> 
> >>> a = 'one'
> >>> b = 'two'
> >>> a, b = b, a
> >>> a
> 'two'
> >>> b
> 'one'
> 
> When there's a tuple on the left of the equals sign the interpreter expects
> a tuple of equal length on the right, and performs element-by-element
> binding in a way which makes the above value interchange possible. The
> absence of parentheses doesn't mean you aren't using tuples...
> 
> regards
>  Steve
> --
> http://www.holdenweb.com/

Tnx, for the clarification...
-- 
------------------------------------------------------------------------------
Tim Daneliuk
tundra at tundraware.com



More information about the Python-list mailing list