Tuples in Python

This is a companion notebook to the Data Science Solutions book.

Unlike a List which is mutable, a Tuple is an immutable data structure in Python. Tuple and lists share several operations as being part of Python sequence types.

When you do not expect the data to change, you may prefer using a Tuple over a List as these perform better.

Define tuples

Tuples can be empty, contain single item, multiple items, mixed data types, nested with other tuples or other sequence types.


In [2]:
# Define a tuple as comma separate values, with(out) enclosing round brackets
number_tuple = 4, 9, 11, 2, 1, 9, 11
number_tuple


Out[2]:
(4, 9, 11, 2, 1, 9, 11)

In [3]:
# Define a mixed data type tuple
mixed_tuple = (1, 'One', 2, 'Two', 3, 'Three')
mixed_tuple


Out[3]:
(1, 'One', 2, 'Two', 3, 'Three')

In [4]:
# Define nested tuple from multiple tuples
nested_tuple = number_tuple, mixed_tuple
nested_tuple


Out[4]:
((4, 9, 11, 2, 1, 9, 11), (1, 'One', 2, 'Two', 3, 'Three'))

In [5]:
# Define tuple of other sequence types
number_list = [1, 2, 3]
simple_string = 'abcdefg'
sequence_tuple = number_list, simple_string, 1, 3
sequence_tuple


Out[5]:
([1, 2, 3], 'abcdefg', 1, 3)

In [6]:
# Define tuple of one item with trailing comma
single_item_tuple = 'One',
single_item_tuple


Out[6]:
('One',)

In [7]:
# Define empty tuple
empty_tuple = ()
empty_tuple


Out[7]:
()

Packing and unpacking tuples

Defining a tuple as comma separated values is also called packing. Unpacking separates the packed values to multiple variables.


In [8]:
packed_tuple = "Jhon", "Doe", 32, "Male"
first, last, age, sex = packed_tuple
print(first, last, age, sex)


('Jhon', 'Doe', 32, 'Male')