2 minute read

A tuple is a data structure that is an immutable, or unchangeable, ordered sequence of elements. Because tuples are immutable, their values cannot be modified.

Tuples are used for grouping data. Each element or value that is inside of a tuple is called an item.

Tuples are similar to lists, but their values can’t be modified. Because of this, when you use tuples in your code, you are conveying to others that you don’t intend for there to be changes to that sequence of values. Additionally, because the values do not change, your code can be optimized through the use of tuples in Python, as the code will be slightly faster for tuples than for lists.

Indexing Tuples

As an ordered sequence of elements, each item in a tuple can be called individually, through indexing.

Each item corresponds to an index number, which is an integer value, starting with the index number 0.

Because each item in a Python tuple has a corresponding index number, we’re able to access items.

Now we can call a discrete item of the tuple by referring to its index number:

In addition to positive index numbers, we can also access items from the tuple with a negative index number, by counting backwards from the end of the tuple, starting at -1.

This is especially useful if we have a long tuple and we want to pinpoint an item towards the end of a tuple.

Slicing Tuples

We can use indexing to call out a few items from the tuple. Slices allow us to call multiple values by creating a range of index numbers separated by a colon [x:y].

When creating a slice, as in [1:3], the first index number is where the slice starts (inclusive), and the second index number is where the slice ends (exclusive), which is why in our example above the items at position, 1 and 2 are the items that print out.

Tuple Functions

There are a few built-in functions that you can use to work with tuples. Let’s look at a few of them.

len()

Like with strings and lists, we can calculate the length of a tuple by using len(), where we pass the tuple as a parameter.

max() and min()

When we work with tuples composed of numeric items, (including integers and floats) we can use the max() and min() functions to find the highest and lowest values contained in the respective tuple.

These functions allow us to find out information about quantitative data, such as test scores, temperatures, prices, etc.