Next / Previous / Contents / Shipman's homepage

12. Type tuple: Immutable sequences

For representing a sequence of values, Python has two similar container types: list and tuple.

An instance of a container type is basically a value that has other values inside it; we call the contained values elements.

So, when should you use a list, and when a tuple? In many contexts, either will work. However, there are important differences.

Write a literal tuple as a sequence of values in parentheses, separated by commas. There may be any number of values of any type or any mixture of types. There may be zero values.

To write a tuple with exactly one value, you must use this special syntax:


That is, you must provide a comma before the closing “)”, in order to show that it is a tuple, and not just a parenthesized expression. Note especially the last two examples below:

>>> ()
>>> ('farcical', 'aquatic', 'ceremony')
('farcical', 'aquatic', 'ceremony')
>>> ('Ni',)
>>> ('Ni')

You may also convert any iterable into a tuple using Section 20.42, “tuple(): Convert to a tuple”.

The tuple type does not have comprehensions (see Section 11.2, “List comprehensions”), but you can get the equivalent by applying the tuple() function to a list comprehension. Here is an example:

>>> tuple([x**2 for x in (2,3,8)])
(4, 9, 64)

Tuples also support the .index() and .count() methods as described in Section 11.1, “Methods on lists”.