bob said unto the world upon 11/01/06 10:47 PM: > At 08:31 PM 1/11/2006, Steve Haley wrote: > >>Hello everyone, >> >>I need to do something very simple but I'm having trouble finding >>the way to do it - at least easily. I have created a tuple and now >>need to find the position of individual members of that >>tuple. Specifically, the tuple is something like: words = ("you", >>"me", "us", "we", "and", "so", "forth") and I need to be able to >>name a member, for example, "us" and find what the position (index) >>of that word is in the tuple. >> >>I would have thought there would be a simple built in function for >>that but I just went through the built in functions in the Python >>Library Reference and I didn't find anything. I could probably >>figure out how to write a while loop or something to do a sequential >>search until I found the right member but I really believe there >>must be an easier way and I'm just not seeing it. You can probably >>tell I'm just learning Python so any help would be appreciated. > > > Unfortunately there is no list method find. Sigh. Here's how I'd do it: > > # create a dictionary with each word as key and ordinal as value > words = dict([(n,m) for m,n in enumerate(("you", "me", "us", "we", > "and", "so", "forth"))]) > words["me"] # returns 1 >
I assume Bob meant that tuples have no index or find method. His suggested procedure will work, but it seems more work than: >>> t = ("I'm", "a", "tuple.", "I", "have", "only", "magic", "methods.") >>> l = list(t) >>> l.index("have") 4 >>> t[4] 'have' >>> I say more work as the way above builds a list to turn into a dictionary. But, since dictionary access is fast, it might be quicker for long tuples where the sought item is near then end. If it matters, test. HTH, Brian vdB _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor