4. Data Structures: Tuples
Tuples
The #\color{#4271ae} {\mathtt{\text{tuple}}}# is another object that is an ordered collection of objects. It is very similar to a #\color{#4271ae} {\mathtt{\text{list}}}# object, but unlike lists tuples are immutable. Once a #\color{#4271ae} {\mathtt{\text{tuple}}}# is defined it cannot be changed. A tuple is defined by specifying comma-separated sequence of objects enclosed in parentheses.
#\mathtt{(}\textit{object}_\textit{0},\textit{object}_\textit{1}, \dots, \textit{object}_\textit{n}\mathtt{)}#
#\color{#4271ae} {\mathtt{tuple}}\mathtt{(}\textit{iterable}\mathtt{)}#
Like lists, tuples also support any type of Python object as element, including more complex ones, such as lists. When you define a comma-separated sequence without any type of brackets, Python will interpret the sequence as a tuple. Syntax like this is very common in #\color{#8959A8} {\mathtt{\text{return}}}# statements and when assigning values to multiple variables on one line.
>>> 1, 2, 3
|
(1, 2, 3)
|
>>> x, y = 1, 2
>>> x |
1
|
Because parentheses are also used for other purposes, a special syntax is required to define a tuple with one element.
>>> (1)
|
1
|
>>> (1,)
|
(1,)
|
Why even use a #\color{#4271ae} {\mathtt{\text{tuple}}}# when you can use a #\color{#4271ae} {\mathtt{\text{list}}}#? There are several reasons to choose tuples over lists. First, since tuples are immutable, operations on them are faster. Second, when in need of a constant iterable, you might prefer a data type that cannot be changed so that it can't be modified accidentally. Another reason is that some data structures only support immutable objects, in that case, you'll have to use a #\color{#4271ae} {\mathtt{\text{tuple}}}# instead.
Naturally, #\color{#4271ae} {\mathtt{\text{tuple}}}# functionality is going to be very similar to that of a #\color{#4271ae} {\mathtt{\text{list}}}#, except for all syntax and methods that allow you to change the contents of a #\color{#4271ae} {\mathtt{\text{list}}}#, which a #\color{#4271ae} {\mathtt{\text{tuple}}}# does not support.
Like lists and strings, tuples also support the same syntax for indexing and slicing.
>>> t = (1, 2, 3, 4, 5)
>>> t[2] |
3
|
>>> t = (1, 2, 3, 4, 5)
>>> t[2:5] |
(3, 4, 5)
|
Or visit omptest.org if jou are taking an OMPT exam.