[Tutor] Tuple indexing
Peter Otten
__peter__ at web.de
Wed Mar 11 16:35:09 CET 2015
Ian D wrote:
> Hi
>
>
>
> I have seen some examples that seem to use a tuple with a method called
> index()
>
>
> The original code I was looking at had this sort of thing:
>
>
>
Hi Ian! Please don't use that much whitespace. It makes your post hard and
unpleasant to read. Thank you.
> SENSORS = ('sensor1', 'sensor2')
>
>
>
> pin_index = SENSORS.index("sensor1")
>
>
> so the result is that pin_index the is equal to 0
>
>
> I then read that a Tuple has no attribute index on this site
> http://www.diveintopython.net/native_data_types/tuples.html
Dive into Python is quite old.
>>>> t.index("example")
> Traceback (innermost last): File "<interactive input>", line 1, in ?
> AttributeError: 'tuple' object has no attribute 'index'
>
>
>
> The example seems to work with 2.7 and 3.3 for me.
The tuple.index() method has been added in Python 2.6:
https://docs.python.org/2.6/whatsnew/2.6.html
"""
Tuples now have index() and count() methods matching the list type’s index()
and count() methods:
>>> t = (0,1,2,3,4,0,1,2)
>>> t.index(3)
3
>>> t.count(0)
2
(Contributed by Raymond Hettinger)
"""
> But I don't find much documentation on indexing Tuples using this method.
> I am just wondering if there is more specific documentation on using
> Tuples this way
Many Python coders don't use tuples to look up an item index; the
traditional application is to pass multiple values around, e. g.
def extent(thing):
x = calculate_width(thing)
y = calculate_height(thing)
return x, y
width, height = extent(picture)
portrait = width < height
In the example you have to know the index beforehand, by reading the code or
its documentation rather than going through all items for a matching item.
When you want to treat all items in a tuple uniformly in most cases using a
tuple is a premature optimisation; use a list or set unless you can name a
compelling reason not to.
Your sensors example could be solved with a dict:
sensors = {"sensor1": 0, "sensor2": 1}
pin_index = sensors["sensor1"]
This approach will still work well for huge numbers of sensors (constant
time or O(1)), unlike tuple/list.index() where the average lookup time grows
with the number of items in the tuple or list (O(n)).
More information about the Tutor
mailing list