Python Tuples

Kind of like a list except immutable. Tuples serve as heterogeneous list.

What are Tuples?

Tuples are similar to lists, except they tend to be designed to be diverse in character as compared to lists in addition to performance advantages.

The performance advantages of Tuples is largely attributed to their immutable nature. The immutability of Tuples enables faster reading and enhanced code safety being that you “write-protect” your data by removing the ability to change it. Click here to learn more about Mutability in Python. Tuples also also provide a logical data structure for holding an object’s with properties where you do not want to create a separate type for it.

Creating a Tuple is simple. Instead of using curly braces such as:

>>> my_list = [1,2]
>>> print(type(my_list))
<class 'list'>

We use the parenthesis to signify the creation of a tuple such as:

my_tuple = (1,2)
<class 'tuple'>

When to use Tuples?

As I stated above, Tuples are great for “holding an object’s with properties”. This means that where it makes logical sense to define properties together always.

If we tried to make a tuple from the given data:

person_name = 'Joe Castille'
person_age = 24
person_role = 'contractor'

person_name = 'Anna Dosier'
person_age = 32
person_role = 'contractor manager'

It wouldn’t make sense to put both people in a Tuple , because we cannot guarantee that two people will always make sense together. What if they are strangers, no longer work together or one becomes deceased?

However, if our user was the ‘contractor manager’ wanting to access data for a contractor under their supervision, loading that data into a Tuple probably would make sense. For the manager session, writing to the contractor name, age, role might not be a concern. Instead our goal may simply be to display this data as quickly as possible to this level of user for read access only, in that case a Tuple is perfect. In this example, we might return contractor data to the manager’s view as such:

def loadContractor():
    my_tuple = ('Joe Castille',24,'contractor')
    return my_tuple


Lastly, in Python Tuples, Sets, and Lists are all built into Python and have easy to use casting. Simply create a new variable and declare the type around your Tuple in order to convert it. As shown:

>>> my_tuple = (1,2)
>>> print(type(my_tuple))

>>> my_list2 = list(my_tuple)
>>> print(type(my_list2))

>>> my_set2 = set(my_tuple)
>>> print(type(my_set2))

<class 'tuple'>
<class 'list'>
<class 'set'>