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.
Values of type list are mutable; that is,
you can delete or add elements, or change the value of any
of the elements inside the list.
Lists cannot be used in certain contexts. For example, you can't use a list as the key in a dictionary.
>>> d={}
>>> d[(23,59)] = 'hike'
>>> d[[46,19]] = 'hut'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
Values of type tuple are immutable. Once
you have assembled a tuple, you cannot add or delete
elements or change the value of an element inside the
tuple.
Among the reasons to use a tuple instead of a list:
Tuples are allowed in certain contexts where lists are not, such as the right-hand argument of the string format operator, or as a key in a dictionary.
If your program is in danger of running out of processor memory, tuples are slightly more efficient in their memory usage.
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:
(value,)
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',)
>>> ('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”.