Home > Dive Into Python > Getting To Know Python > Tuples 101 | << >> | ||||
Dive Into Python Python for experienced programmers |
A tuple is an immutable list. A tuple can not be changed in any way once it is created.
Example 1.23. Defining a tuple
>>> t = ("a", "b", "mpilgrim", "z", "example")>>> t ('a', 'b', 'mpilgrim', 'z', 'example') >>> t[0]
'a' >>> t[-1]
'example' >>> t[1:3]
('b', 'mpilgrim')
Example 1.24. Tuples have no methods
>>> t ('a', 'b', 'mpilgrim', 'z', 'example') >>> t.append("new")Traceback (innermost last): File "<interactive input>", line 1, in ? AttributeError: 'tuple' object has no attribute 'append' >>> t.remove("z")
Traceback (innermost last): File "<interactive input>", line 1, in ? AttributeError: 'tuple' object has no attribute 'remove' >>> t.index("example")
Traceback (innermost last): File "<interactive input>", line 1, in ? AttributeError: 'tuple' object has no attribute 'index' >>> "z" in t
1
So what are tuples good for?
![]() | |
Tuples can be converted into lists, and vice-versa. The built-in tuple function takes a list and returns a tuple with the same elements, and the list function takes a tuple and returns a list. In effect, tuple freezes a list, and list thaws a tuple. |
Further reading
Footnotes
[2] [2] Actually, it's more complicated than that. Dictionary keys must be immutable. Tuples themselves are immutable, but if you have a tuple of lists, that counts as mutable and isn't safe to use as a dictionary key. Only tuples of strings, numbers, or other dictionary-safe tuples can be used as dictionary keys.
Lists 101 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Defining variables |