next up previous contents
Next: Dictionaries Up: Lists, Tuples and Dictionaries Previous: Operators and Indexing for   Contents

Functions and Methods for Tuples

Since tuples and lists are so similar, it's not surprising that there are times when you'll need to convert between the two types, without changing the values of any of the elements. There are two builtin functions to take care of this: list, which accepts a tuple as its single argument and returns a list with identical elements, and tuple which accepts a list and returns a tuple. These functions are very useful for resolving TypeError exceptions involving lists and tuples.

There are no methods for tuples; however if a list method which doesn't change the tuple is needed, you can use the list function to temporarily change the tuple into a list to extract the desired information.

Suppose we wish to find how many times the number 10 appears in a tuple. The count method described in Section 4.4 can not be used on a tuple directly, since an AttributeError is raised:

>>> v = (7,10,12,19,8,10,4,13,10)
>>> v.count(10)
Traceback (innermost last):
  File "<stdin>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'count'
To solve the problem, call the list function with the tuple as its argument, and invoke the desired method directly on the object that is returned:
>>> list(v).count(10)
3
Note, however, that if you invoke a method which changes or reorders the values of a temporary list, python will not print an error message, but no change will be made to the original tuple.
>>> a = (12,15,9)
>>> list(a).sort()
>>> a
(12, 15, 9)
In case like this, you'd need to create a list, invoke the method on that list, and then convert the result back into a tuple.
>>> aa = list(a)
>>> aa.sort()
>>> a = tuple(aa)
>>> a
(9, 12, 15)


next up previous contents
Next: Dictionaries Up: Lists, Tuples and Dictionaries Previous: Operators and Indexing for   Contents
Phil Spector 2003-11-12