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.
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]:
In [3]:
# Define a mixed data type tuple
mixed_tuple = (1, 'One', 2, 'Two', 3, 'Three')
mixed_tuple
Out[3]:
In [4]:
# Define nested tuple from multiple tuples
nested_tuple = number_tuple, mixed_tuple
nested_tuple
Out[4]:
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]:
In [6]:
# Define tuple of one item with trailing comma
single_item_tuple = 'One',
single_item_tuple
Out[6]:
In [7]:
# Define empty tuple
empty_tuple = ()
empty_tuple
Out[7]:
In [8]:
packed_tuple = "Jhon", "Doe", 32, "Male"
first, last, age, sex = packed_tuple
print(first, last, age, sex)