Tuple index

John Machin sjmachin at lexicon.net
Sun Feb 20 21:05:59 EST 2005


Steve M wrote:
> Hello,
>
>         I'm trying to figure out the index position of a tuple
member.
> I know the member name, but I need to know the members index
position.

Tuples, like lists, don't have members in the sense that they can be
"named" like t.foo. The only way of referring to them is by index,
t[4].

> I
> know that if I use the statement print tuple[4] that it will print
the
> contents of that location. What I don't understand is if I know that
foo is
> a member of tuple, how do I get foo's index position.

You *can't* "know that foo is a member of tuple".

Consider this:

>>> foo = 'carol'
>>> t = (123,456,789,'bob',foo,'ted')
>>> t[4]
'carol'

Is that what you mean by "foo is a member of t'? Well, it's not. foo is
a reference to the string 'carol'. t[4] is also a reference to the
string 'carol'.

Now read on ...

>>> foo = 'alice'
>>> t
(123, 456, 789, 'bob', 'carol', 'ted')
>>> t[4]
'carol'
>>>

Now foo is a reference to the string 'alice'. Nothing to do with t,
either before or now.

Have you read the tutorial found at http://docs.python.org/tut/tut.html
?




More information about the Python-list mailing list