473,662 Members | 2,390 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4035
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,'b ob',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,'b ob',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).i ndex(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#wh y-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).i ndex(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

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

Similar topics

0
1370
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 ); iobj->ob_ival = val; PyTuple_SetItem( tuple, index, iobj ); return tuple; while the following will collect the elements: PyTuple_SetItem( tuple, index PyInt_FromLong( val ) );
3
1369
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
3677
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, I'm just curious why it is neccesary.. Thanks,
3
9683
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 script I get the following interpreter error.
6
1714
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, which looks like a tuple but also like a struct. That is, I can do: >>> time.localtime() (2006, 1, 18, 21, 15, 11, 2, 18, 0) >>> time.localtime() 21 >>> time.localtime().tm_hour
6
1562
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: Point=superTuple("x","y","z") # this is a class factory p=Point(4,7,9) assert p.x==p
77
4411
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 Maclaren.
12
4150
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 like this: ('eco', "(u'Roads',)", 0.073969887301348305) Pysqlite doesn't like the format of the middle term: pysqlite2.dbapi2.InterfaceError: Error binding parameter 1 - probably
2
6025
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. Let me lay out (in a fresh way) why I think we should reconsider. 1) It's counterintuitive to exclude them: It makes very little sense why an indexable data structure wouldn't have .index() as a method. It makes even less sense to not allow...
0
8432
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8762
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8545
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7365
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5653
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4179
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4347
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1992
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.