Tuples

NoteWhat is a tuple?

Tuples are sequences of immutable Python objects. They are similar to lists, but they are immutable. Tuples are created by enclosing a comma-separated list of values in parentheses.

NoteAre Tuples mutable?

Tuples are immutable, which means that once they are created, they cannot be changed!!

NoteWhy should I use tuples?

Tuples are useful for storing data that is not to be changed, such as the coordinates of a point in a two-dimensional space. In general, we use tuples any time information integrity is a concern — in other words when we want to ensure the information included in an object will not change because of another reference in our program.

NoteHow do I create a tuple?

Python objects, separated by a comma, must be included between parentheses (see Snippet 4.19, line 2).

NoteHow do I access the information in a tuple?

By positional offsets, like lists (see Snippet 4.19, lines 5 and 9).

# the tuple
>>> T = ("Captain Marvel", 3)

# access a tuple element
>>> T[0]
"Captain Marvel"

# access a tuple element
>>> T[1]
3
NoteCan I convert a tuple into a list?

Yes, you can. To do that, you must pass the tuple as the argument of list (see Snippet 4.20).

>>> T = ("Captain Marvel", 3)

# from a tuple to a list
>>> L = list(T)
>>> print(L)
["Captain Marvel", 3]

# amend L's items
>>> L[1] = 4

# get back to a tuple
>>> T = tuple(L)
>>> print(T)
("Captain Marvel", 4)
NoteCan I create an advanced data container based on a tuple?

collections is a module that is shipped with Python and provides data containers that are alternative to Python’s general purpose built-in containers, i.e., dict, list, set, and tuple. One of these containers can be created with the function namedtuple (see Snippet 4.21), which allows annotating the tuple items with names. In line 2, we import the function namedtuple from the collections module. In line 5, we create an ad hoc class that best represents the structure of our sample data concerning Marvel characters’ names and the year they first appeared in the comic series. The first argument taken by the function is customary and regards the name of the class we are about to create. The second argument is a list with the names of the attributes included in our data structure. In line 8, we use the newly created class Rec to create a tuple, which is eventually printed as per line 11.

# import the named tuple function from the module collection
>>> from collections import namedtuple

# create an ad hoc class object 'Rec' that fits our data structure
>>> Rec = namedtuple("Rec", ["character", "first_appearance"])

# use the generated class "Rec"
>>> IRONMAN = Rec("Iron Man", 1963)

# A named-tuple record
>>> IRONMAN
Rec(character="Iron Man", first_appearance=1963)