Tuple index

Steve M steve at myplace.com
Mon Feb 21 16:54:10 EST 2005


Steven Bethard wrote:

> Steve M wrote:
>> I guess I explained my problem incorrectly. Let me try again.
>> 
>> tuple = ("fred", "barney", "foo")
>> 
>> I know that foo is an element of tuple, but what I need to know is what
>> the index of foo is, tuple[?].
> 
> Larry Bates's solution is probably the best way to go here:
> 
> py> t = ("fred", "barney", "foo")
> py> list(t).index("foo")
> 2
> py> t[2]
> 'foo'
> 
> But note that if you're doing this often, you're probably using tuple
> for the wrong things.  Check out:
> 
> http://www.python.org/doc/faq
general.html#why-are-there-separate-tuple-and-list-data-types
> 
> If you're iterating over the items of something and the items are all of
>   the same type, you probably want a list, not a tuple.
> 
> What's the use case in which you want to do this?
> 
> STeVe

I'm actually doing this as part of an exercise from a book. What the program
is supposed to do is be a word guessing game. The program automaticly
randomly selects a word from a tuple. You then have the oportunity to ask
for a hint. I created another tuple of hints, where the order of the hints
correspond to the word order. I was thinking if I could get the index
position of the randomly selected word, I pass that to the hints tuple to
display the correct hint from the hints tuple. I'm trying to do it this way
as the book I'm using has not gotten to lists yet. As you may have guessed,
I'm just learning Python. I do appreciate your help, Thank you.

Steve



More information about the Python-list mailing list