[Tutor] Finding the Index of a member of a Tuple

Terry Carroll carroll at tjc.com
Thu Jan 12 08:04:08 CET 2006


On Wed, 11 Jan 2006, Steve Haley wrote:

> I need to do something very simple but I'm having trouble finding the way to
> do it - at least easily.  I have created a tuple and now need to find the
> position of individual members of that tuple.  Specifically, the tuple is
> something like: words = ("you", "me", "us", "we", "and", "so", "forth") and
> I need to be able to name a member, for example, "us" and find what the
> position (index) of that word is in the tuple.

Does it have to be a tuple?  If you make it a list, you can use index():

>>> words = ["you", "me", "us", "we", "and", "so", "forth"]
>>> words.index("and")
4

If it must be a tuple, you can't do that directly:

>>> words = ("you", "me", "us", "we", "and", "so", "forth")
>>> words.index("and")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'index'


but you can wrap it in a list conversion:

>>> words = ("you", "me", "us", "we", "and", "so", "forth")
>>> list(words).index("and")
4

I'm not sure why tuple wouldn't have this capability; but it doesn't.



More information about the Tutor mailing list