Member index in toples

skip at pobox.com skip at pobox.com
Thu Jun 1 14:29:55 EDT 2006


    Alan> T = ("One","Two","Three","Four")

    Alan> Is there any built-in way to find what is the index of "Two"
    Alan> withouot looping within the tuple?

One thing to consider is the different uses intended for tuples and lists.
Tuples should not be treated as immutable lists, though many people use them
that way.  Think of lists as arrays of objects of uniform type.  Think of
tuples more like Pascal records or C structs.  You probably want to use a
list in the above case.

That said, note that Python provides lots of introspection capability.  Try
this at an interpreter prompt:

    T = ("One","Two","Three","Four")
    L = list(T)
    help(L)

or from a shell prompt:

    pydoc list

The help it returns suggests that

    L.index("Two")

will tell you the index of "Two" in L.

    Alan> Is the same feature available for lists or dictionaries?

Dictionaries are inherently unordered.  You probably want to consider the
truth of this expression:

    "Two" in mydict

for a suitably defined dictionary.  It answers whether "Two" exists as a key
in mydict.

Skip



More information about the Python-list mailing list