Newbie question on tuples

T

Thomas Philips

How does one find the position of an item in a tuple. i.e. If the
tuple is ("rock", "scissors", "paper"), what function (or method) do I
call with "rock" to get 0 or with "paper" to get 2?

Thomas Philips
 
S

Skip Montanaro

Thomas> How does one find the position of an item in a tuple. i.e. If
Thomas> the tuple is ("rock", "scissors", "paper"), what function (or
Thomas> method) do I call with "rock" to get 0 or with "paper" to get 2?

Tuples don't have an index method, but lists do, so you can list-ify your
tuple:
2

Skip
 
J

Jonathan Daugherty

# Tuples don't have an index method, but lists do, so you can list-ify your
# tuple:

They most certainly do.

--

Jonathan Daugherty
http://www.cprogrammer.org

"It's a book about a Spanish guy called Manual, you should read it."
-- Dilbert
 
C

Carmine Noviello

How does one find the position of an item in a tuple. i.e. If the
tuple is ("rock", "scissors", "paper"), what function (or method) do I
call with "rock" to get 0 or with "paper" to get 2?

Thomas Philips

def indexOf(t, elem):
ret = -1 #Not in tuple
for i in range(len(t)):
if t == elem:
ret = i
break
return ret

-Bye
 
D

djw

Jonathan said:
# Tuples don't have an index method, but lists do, so you can list-ify your
# tuple:

They most certainly do.

--

Jonathan Daugherty
http://www.cprogrammer.org

"It's a book about a Spanish guy called Manual, you should read it."
-- Dilbert

Huh?
Traceback (most recent call last):

-D
 
J

Jonathan Daugherty

# Huh?
#
# >>> ("rock", "scissors", "paper").index("rock")
# Traceback (most recent call last):
# File "<interactive input>", line 1, in ?
# AttributeError: 'tuple' object has no attribute 'index'
# >>>

I thought he meant [].

--

Jonathan Daugherty
http://www.cprogrammer.org

"It's a book about a Spanish guy called Manual, you should read it."
-- Dilbert
 

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

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,950
Members
47,503
Latest member
supremedee

Latest Threads

Top