Tuple index
Michael Hartl
mhartl at post.harvard.edu
Mon Feb 21 16:30:22 EST 2005
I actually find it strange that tuples don't have an index function,
since finding the index doesn't involve any mutation. Anyone know why
Python doesn't allow a statement like t.index('foo')?
In any case, you can use the index method of list objects if you
convert your tuple to a list first:
>>> t = ("fred", "barney", "foo")
>>> list(t).index("foo")
2
>>> def index(a_tuple, element):
... return list(a_tuple).index(element)
...
>>> t[index(t, "foo")]
'foo'
(By the way, 'tuple' is a Python built-in type, so it's probably best
to avoid using it as a variable name.)
Michael
--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/
More information about the Python-list
mailing list