Indexing Into A Tuple

Steve Holden sholden at holdenweb.com
Wed Jun 27 19:51:51 CEST 2001


"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/








More information about the Python-list mailing list