473,396 Members | 2,013 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Tuple index

Hello,

I'm trying to figure out the index position of a tuple member.
I know the member name, but I need to know the members index position. I
know that if I use the statement print tuple[4] that it will print the
contents of that location. What I don't understand is if I know that foo is
a member of tuple, how do I get foo's index position.
Thanks-in-Advance
Steve
Jul 18 '05 #1
15 4016
Tuples don't have all the nice methods that lists have
so convert it to a list.

tuple=('a','b','c','d')
l=list(tuple)

now you can do:

list.index('c')

which returns 2

Remember index returns -1 when nothing is found.

Larry Bates
Steve M wrote:
Hello,

I'm trying to figure out the index position of a tuple member.
I know the member name, but I need to know the members index position. I
know that if I use the statement print tuple[4] that it will print the
contents of that location. What I don't understand is if I know that foo is
a member of tuple, how do I get foo's index position.
Thanks-in-Advance
Steve

Jul 18 '05 #2
Larry Bates wrote:
Tuples don't have all the nice methods that lists have
so convert it to a list.

tuple=('a','b','c','d')
l=list(tuple)

now you can do:

list.index('c')

which returns 2

Remember index returns -1 when nothing is found.


No, that's .find in strings that returns -1. .index in lists raises a
ValueError:
[1, 2, 3].index(4)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: list.index(x): x not in list

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
The map is not the territory.
-- Alfred Korzybski
Jul 18 '05 #3

Steve M wrote:
Hello,

I'm trying to figure out the index position of a tuple member. I know the member name, but I need to know the members index position.

Tuples, like lists, don't have members in the sense that they can be
"named" like t.foo. The only way of referring to them is by index,
t[4].
I
know that if I use the statement print tuple[4] that it will print the contents of that location. What I don't understand is if I know that foo is a member of tuple, how do I get foo's index position.


You *can't* "know that foo is a member of tuple".

Consider this:
foo = 'carol'
t = (123,456,789,'bob',foo,'ted')
t[4] 'carol'

Is that what you mean by "foo is a member of t'? Well, it's not. foo is
a reference to the string 'carol'. t[4] is also a reference to the
string 'carol'.

Now read on ...
foo = 'alice'
t (123, 456, 789, 'bob', 'carol', 'ted') t[4] 'carol'


Now foo is a reference to the string 'alice'. Nothing to do with t,
either before or now.

Have you read the tutorial found at http://docs.python.org/tut/tut.html
?

Jul 18 '05 #4
John Machin wrote:

Steve M wrote:
Hello,

I'm trying to figure out the index position of a tuple

member.
I know the member name, but I need to know the members index

position.

Tuples, like lists, don't have members in the sense that they can be
"named" like t.foo. The only way of referring to them is by index,
t[4].
I
know that if I use the statement print tuple[4] that it will print

the
contents of that location. What I don't understand is if I know that

foo is
a member of tuple, how do I get foo's index position.


You *can't* "know that foo is a member of tuple".

Consider this:
foo = 'carol'
t = (123,456,789,'bob',foo,'ted')
t[4] 'carol'

Is that what you mean by "foo is a member of t'? Well, it's not. foo is
a reference to the string 'carol'. t[4] is also a reference to the
string 'carol'.

Now read on ...
foo = 'alice'
t (123, 456, 789, 'bob', 'carol', 'ted') t[4] 'carol'


Now foo is a reference to the string 'alice'. Nothing to do with t,
either before or now.

Have you read the tutorial found at http://docs.python.org/tut/tut.html
?


I guess I explained my problem incorrectly. Let me try again.

tuple = ("fred", "barney", "foo")

I know that foo is an element of tuple, but what I need to know is what
the index of foo is, tuple[?]. Hopefully this explains what I'm trying
do do better. Sorry about the earlier confusion.

Steve
Jul 18 '05 #5
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/

Jul 18 '05 #6
Steve M wrote:
I guess I explained my problem incorrectly. Let me try again.

tuple = ("fred", "barney", "foo")

I know that foo is an element of tuple, but what I need to know is what
the index of foo is, tuple[?].


Larry Bates's solution is probably the best way to go here:

py> t = ("fred", "barney", "foo")
py> list(t).index("foo")
2
py> t[2]
'foo'

But note that if you're doing this often, you're probably using tuple
for the wrong things. Check out:

http://www.python.org/doc/faq/genera...ist-data-types

If you're iterating over the items of something and the items are all of
the same type, you probably want a list, not a tuple.

What's the use case in which you want to do this?

STeVe
Jul 18 '05 #7
Michael Hartl wrote:
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')?


Tuples aren't really intended for this kind of use. See:

http://www.python.org/doc/faq/genera...ist-data-types

Tuples are supposed to be operated on as a group. It's even been
suggested occasionally on python-dev that in Python 3.0, tuples
shouldn't support iteration at all...

STeVe
Jul 18 '05 #8
Steven Bethard wrote:
Steve M wrote:
I guess I explained my problem incorrectly. Let me try again.

tuple = ("fred", "barney", "foo")

I know that foo is an element of tuple, but what I need to know is what
the index of foo is, tuple[?].
Larry Bates's solution is probably the best way to go here:

py> t = ("fred", "barney", "foo")
py> list(t).index("foo")
2
py> t[2]
'foo'

But note that if you're doing this often, you're probably using tuple
for the wrong things. Check out:

http://www.python.org/doc/faq

general.html#why-are-there-separate-tuple-and-list-data-types
If you're iterating over the items of something and the items are all of
the same type, you probably want a list, not a tuple.

What's the use case in which you want to do this?

STeVe


I'm actually doing this as part of an exercise from a book. What the program
is supposed to do is be a word guessing game. The program automaticly
randomly selects a word from a tuple. You then have the oportunity to ask
for a hint. I created another tuple of hints, where the order of the hints
correspond to the word order. I was thinking if I could get the index
position of the randomly selected word, I pass that to the hints tuple to
display the correct hint from the hints tuple. I'm trying to do it this way
as the book I'm using has not gotten to lists yet. As you may have guessed,
I'm just learning Python. I do appreciate your help, Thank you.

Steve
Jul 18 '05 #9
Michael Hartl wrote:
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/


The book I'm using to learn Python with has not gotten to lists yet, maybe
next chapter.

I knew tuple is a built in type, I was just trying to be clear, I guess I
just muddied the water a bit. Thank you for your help.

Steve
Jul 18 '05 #10

Steve M wrote:
I'm actually doing this as part of an exercise from a book. What the program is supposed to do is be a word guessing game. The program automaticly
randomly selects a word from a tuple.


Care to tell us which book is using a tuple for this, but hasn't got to
lists yet?

Cheers,
John

Jul 18 '05 #11
Steve M wrote:
I'm actually doing this as part of an exercise from a book. What the program
is supposed to do is be a word guessing game. The program automaticly
randomly selects a word from a tuple. You then have the oportunity to ask
for a hint. I created another tuple of hints, where the order of the hints
correspond to the word order. I was thinking if I could get the index
position of the randomly selected word, I pass that to the hints tuple to
display the correct hint from the hints tuple. I'm trying to do it this way
as the book I'm using has not gotten to lists yet.


I'm guessing it also hasn't gotten to dicts yet either? Perhaps a
somewhat more natural way of doing this would be something like:

py> hints = dict(word1="here's hint 1!",
.... word2="here's hint 2!",
.... word3="here's hint 3!")
py> words = list(hints)
py> import random
py> selected_word = random.choice(words)
py> selected_word
'word3'
py> print hints[selected_word]
here's hint 3!

That said, if you want to find the index of a word in a tuple without
using list methods, here are a couple of possibilities, hopefully one of
which matches the constructs you've seen so far:

py> t = ("fred", "barney", "foo")

py> for i, word in enumerate(t):
.... if word == "barney":
.... break
....
py> i
1

py> for i in range(len(t)):
.... if t[i] == "barney":
.... break
....
py> i
1

py> i = 0
py> for word in t:
.... if word == "barney":
.... break
.... i += 1
....
py> i
1

HTH,

STeVe
Jul 18 '05 #12
John Machin wrote:

Steve M wrote:
I'm actually doing this as part of an exercise from a book. What the

program
is supposed to do is be a word guessing game. The program automaticly
randomly selects a word from a tuple.


Care to tell us which book is using a tuple for this, but hasn't got to
lists yet?

Cheers,
John


Python Programming for the absoulte beginner by Michael Dawson

Steve
Jul 18 '05 #13
Steven Bethard wrote:
Steve M wrote:
I'm actually doing this as part of an exercise from a book. What the
program is supposed to do is be a word guessing game. The program
automaticly randomly selects a word from a tuple. You then have the
oportunity to ask for a hint. I created another tuple of hints, where the
order of the hints correspond to the word order. I was thinking if I
could get the index position of the randomly selected word, I pass that
to the hints tuple to display the correct hint from the hints tuple. I'm
trying to do it this way as the book I'm using has not gotten to lists
yet.


I'm guessing it also hasn't gotten to dicts yet either? Perhaps a
somewhat more natural way of doing this would be something like:

py> hints = dict(word1="here's hint 1!",
... word2="here's hint 2!",
... word3="here's hint 3!")
py> words = list(hints)
py> import random
py> selected_word = random.choice(words)
py> selected_word
'word3'
py> print hints[selected_word]
here's hint 3!

That said, if you want to find the index of a word in a tuple without
using list methods, here are a couple of possibilities, hopefully one of
which matches the constructs you've seen so far:

py> t = ("fred", "barney", "foo")

py> for i, word in enumerate(t):
... if word == "barney":
... break
...
py> i
1

py> for i in range(len(t)):
... if t[i] == "barney":
... break
...
py> i
1

py> i = 0
py> for word in t:
... if word == "barney":
... break
... i += 1
...
py> i
1

HTH,

STeVe


Thanks Steve, I'll see if I can make that solution work for me.

Steve
Jul 18 '05 #14

Steve M wrote:
John Machin wrote:

Steve M wrote:
I'm actually doing this as part of an exercise from a book. What the
program
is supposed to do is be a word guessing game. The program
automaticly randomly selects a word from a tuple.


Care to tell us which book is using a tuple for this, but hasn't

got to lists yet?

Cheers,
John


Python Programming for the absoulte beginner by Michael Dawson


In a review I found on the web:
http://www.skattabrain.com/css-books...592000738.html
"Dawson will take you by the hand and lead you down the garden path."

Malapropism? Intentional humour?

Jul 18 '05 #15
On 21 Feb 2005 15:01:05 -0800, "John Machin" <sj******@lexicon.net>
wrote:

Steve M wrote:
John Machin wrote:
>
> Steve M wrote:
>> I'm actually doing this as part of an exercise from a book. Whatthe > program
>> is supposed to do is be a word guessing game. The programautomaticly >> randomly selects a word from a tuple.
>
> Care to tell us which book is using a tuple for this, but hasn'tgot to > lists yet?
>
> Cheers,
> John


Python Programming for the absoulte beginner by Michael Dawson


In a review I found on the web:
http://www.skattabrain.com/css-books...592000738.html
"Dawson will take you by the hand and lead you down the garden path."

Malapropism? Intentional humour?


The book teaches you enough about programming and python to get you
programming. It was the only python book in my local library so I
read it while trying to learn the basics of python. It got me to the
point where I could comfortably write Fortran-style python (I am not
claiming that anyone else will leave the book that way, only that was
as far as I had progressed in understanding python).

I think that this book suggests using pickle/unpickle to send data
over the internet. This is an amazingly bad idea, which is obvious
once you understand how overloading works (I'm pretty sure overloading
isn't covered in that book).

In short, I think that this book is a good introduction to
programming, and it will explain the basics of python, but it doesn't
really begin to explain how to program in python.

Scott Robinson

Jul 18 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Ron Griswold | last post by:
Can anyone tell me why the following will cause the returned tuple elements to remain un collected when the tuple goes out of scope: PyObject * iobj = PyObject_New( PyIntObject, &PyInt_Type );...
3
by: Jinming Xu | last post by:
Sorry for the previous message. It's really a simple question and I have solved it myself. Thanks, Jinming ------------------------------------------------------------------------ Hi Folks,
50
by: Will McGugan | last post by:
Hi, Why is that a tuple doesnt have the methods 'count' and 'index'? It seems they could be present on a immutable object. I realise its easy enough to convert the tuple to a list and do this,...
3
by: Rakesh | last post by:
In my Python code fragment, I want to write a code fragment such that the minimum element of a tuple is subtracted from all the elements of a given tuple. When I execute the following python...
6
by: groups.20.thebriguy | last post by:
I've noticed that there's a few functions that return what appears to be a tuple, but that also has attributes for each item in the tuple. For example, time.localtime() returns a time.time_struct,...
6
by: alainpoint | last post by:
Hello, I have got a problem that i can't readily solve. I want the following: I want to create a supertuple that behaves both as a tuple and as a class. It should do the following:...
77
by: Nick Maclaren | last post by:
Why doesn't the tuple type have an index method? It seems such a bizarre restriction that there must be some reason for it. Yes, I know it's a fairly rare requirement. Regards, Nick...
12
by: rshepard | last post by:
I'm a bit embarrassed to have to ask for help on this, but I'm not finding the solution in the docs I have here. Data are assembled for writing to a database table. A representative tuple looks...
2
by: hall.jeff | last post by:
Before the inevitable response comes, let me assure you I've read through the posts from Guido about this. 7 years ago Guido clearly expressed a displeasure with allowing these methods for tuple....
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.