Tuples
Python also provides another sequence type called tuple
s.
Tuples are like lists. The main difference is that lists are mutable (can be modified), while tuples are immutable (cannot be changed).
So you cannot add/remove items to/from a tuple
once you have created it.
Tuples are useful for representing ordered, fixed-size grouping of elements, like 2D coordinates \((x, y)\) or 3D coordinates \((x, y, z)\).
Creating a new tuple
is just like creating a list
, except that you use (
parenthesis)
instead of [
square brackets]
.
>>> my_vector = (1, 3, 4)
>>> print(my_vector)
You can also convert an existing list
(or any Python sequence type) into a new tuple
object.
>>> my_list = [1, 3, 4]
>>> my_vector = tuple(my_list)
>>> print(my_vector)
You can use tuple
s just like you would use list
s:
>>> x = (1, 2, 3, 4, 5)
>>> print(x[0])
>>> print(x[1:3])
>>> print(x[-1])
>>> print(x[:4:2])
>>> print(x[::-1])
… except that you cannot modify the elements. Try the following, and understand the error messages produced by Python.
>>> x[1] = 6 # Python will complain!
>>> x.append(6) # ... and complain again!
A Python quirk! If your tuple has one single element, you should include a comma after the first element to indicate that it is a tuple. Otherwise, Python will treat it as a single variable (the parenthesis will just be a parenthesis). Ugly, I know.
>>> non_tuple = (1)
>>> print(non_tuple)
>>> print(type(non_tuple))
>>> singleton = (1,)
>>> print(singleton)
>>> print(type(singleton))