Member index in toples

A

A.M

Hi,



I have a tuple like this:



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



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



Is the same feature available for lists or dictionaries?



Thank you,

Alan
 
K

Klaus Alexander Seistrup

A.M skrev:
I have a tuple like this:

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

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

Is the same feature available for lists or dictionaries?

Lists have an index method:

#v+

#v-

Dictionaries are unordered and hence indices don't make much sense.

Mvh,
 
S

skip

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
 
T

Tim Chase

I have a tuple like this:
T = ("One","Two","Three","Four")

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

Is the same feature available for lists or dictionaries?

Lists have a index() method. For the tuple, you can convert it
to a list:

indexOfTwo = list(T).index("Two")

Dictionaries don't have a defined ordering, so there's no similar
functionality (because results would be meaningless) unless you
convert it to a list, and then you can snag its index in the
arbitrarily-ordered results (or sort the results first).

If you just need to test for presence, and don't need the index,
you can use

"Two" in T

Just a few ideas...

-tkc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,297
Messages
2,571,536
Members
48,282
Latest member
Xyprime

Latest Threads

Top