top of page

Mastering Python Tuples: A Complete Guide

Updated: Feb 17, 2023

A tuple is a data structure that behaves the same as a list with only one key difference; they are immutable. Once a tuple has been created, unlike a list, the elements stored within can not be modified. This makes tuples useful for storing data that should not be changed, such as coordinates or a specific date.


In this blog post, we'll cover the following topics:


Creating a Tuple

There are a few ways you can create a tuple. The easiest, by far, has to be with parentheses. In Python, parentheses around items separated by commas indicate a tuple. Here's an example of a tuple that contains the integers 1-5:

my_tuple = (1, 2, 3, 4, 5)

A list in Python can store any data type you'd like, including a collection of mixed types, such as integers and strings. Below I provide a few more examples of lists:

my_tuple1 = ("Python", "Java", "Rust", "C++")
my_tuple2 = ("1", 2, "3", 4, "5")

If you've ever worked with lists, you'll see similarities in how we define each. For lists, we use square brackets, but tuples use parentheses.



Accessing Items

A tuple wouldn't be much use if we couldn't access the individual items within the tuple. To extract a specific item from a tuple, we'll use a concept called indexing. Indexing is a way to reference an element within a collection, a tuple in this case, by some positional value with the bounds [0, length-1]. Notice that the range of possible values starts at zero. This is important because the first item's index value in any collection is always zero and never one.


Looking at the `my_tuple` variable, the bounds of possible index values are from [0, 4], with the integer 1 having an index value of 0 and 5 an index value of 4. The end value of 4 came from counting the total number of items in the tuple and subtracting one from the result. To extract a specific item, we surround an index value with the bracket symbol "[index]" and place it to the right of the variable name.


Here's an example of this:

my_tuple = (1, 2, 3, 4, 5)
item = my_tuple[0]  # Index of 0
print(item)

# Output: 1

If the last element is desired, we can do the following:

my_tuple = (1, 2, 3, 4, 5)
item = my_tuple[4]  # Index of 4
print(item)

# Output: 5

While most index values will be specified as positive integers, it is possible to specify negative integer values. In the case of negative values, the bounds on possible values then become [-length, -1] where `-length` corresponds to an index value of 0 and -1 to an index value of 4 if we continue using the `my_tuple` variable as a reference.


While negative integer values might not seem very beneficial at first glance, they can be a lifesaver when you need the second to last element in a collection and don't know or want to calculate the length. It can also make your code much more readable because you no longer need to subtract values from the length to get at the elements you want.


Here are the two examples from above; only this time, we'll use negative index values to get the desired integers.

my_tuple = (1, 2, 3, 4, 5)
item = my_tuple[-5]  # Index of -5
print(item)

# Output: 1
my_tuple = (1, 2, 3, 4, 5)
item = my_tuple[-1]  # Index of -1
print(item)

# Output: 5


Slicing

Slicing builds on the indexing principle discussed above; rather than obtaining one element from the collection (one item from the tuple), we can extract many or all parts from the collection. The basic syntax for slicing is as follows:

tuple[start : end]

Where `tuple` is the original tuple, `start` is the starting index (inclusive), and `end` is the stopping index (exclusive). Looking at the `my_tuple` variable again, we can extract the values 2, 3, and 4 with the following slice:

item = my_tuple[1:4]

To test that the slice does extract the values 2, 3, and 4, run the following code:

my_tuple = (1, 2, 3, 4, 5)
item = my_tuple[1:4]
print(item)

# Output: (2, 3, 4)

You can also omit the start or end index; sometimes, you can leave out both altogether. Here's an example of leaving out the end index to extract the integers 4 and 5 from the `my_tuple` variable:

my_tuple = (1, 2, 3, 4, 5)
item = my_tuple[3:]  # Omit the end index
print(item)

# Output: (4, 5)

Negative index values are also allowed when slicing a collection. Here's an example of omitting the start index and specifying the end as a negative index value to extract the integers 1 and 2:

my_tuple = (1, 2, 3, 4, 5)
item = my_tuple[:-3]  # Omit the start index
print(item)

# Output: (1, 2)

One last thing you can do with slicing is specify a step value to select every nth character. The basic syntax for slicing a tuple with a step value is as follows:

tuple[start : end : step]

The `tuple`, `start`, and `end` are the same as defined above, and the `step` is the number of items you want to skip. Here's an example of how you could select every other item from a tuple:

my_tuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
item = my_tuple[::2]  # Omit start/end index values
print(item)

# Output: (0, 2, 4, 6, 8)

By omitting the start and end index, we select all items in the tuple, and the step value selects every two items starting at first.


We can also use negative values for the step, allowing for some interesting behavior. Here's an example of how you can reverse the order of a tuple with slicing:

my_tuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
item = my_tuple[::-1]  # Omit start/end index values
print(item)

# Output: (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)

Tuple Unpacking

One of the more powerful features tuples provide is the ability to assign each element within the tuple to individual variables. Below is an example of tuple unpacking.

(1) my_tuple = ("Jason", 23)
(2) name, age = my_tuple  # tuple unpacking
(3) print(name, age)

Output: Jason 23

Looking at the above code, in section one, a tuple containing a name and age is stored in a variable called `my_tuple`. In section two, we unpack the elements in the tuple into two new variables called `name` and `age`. Then, in section 3, we print the name and age. You could use indexing in the print statement to achieve the same results, but your code becomes more readable by utilizing tuple unpacking.



Common Functions and Methods to Manipulate Tuples

Function/Method

Definition

tuple(iterable)

Converts an iterable to a tuple

len(iterable)

Returns the number of items in a list

iter.count(item)

​returns the number of times a specific value appears in a collection

iter.index(item)

returns the index of the first occurrence of a specific value in a collection

Note that the "iter." in the table is the variable that contains the iterable/collection you want to apply the method to. In our case, it's a tuple but could easily be a list, set, or string.


Using Python's `tuple` Function

The `tuple` function converts an iterable to a tuple. Below I show how to convert a string to a tuple.

my_str = "Hello!"
my_tuple = tuple(my_str)
print(my_tuple)

# Output: ('H', 'e', 'l', 'l', 'o', '!')

Using Python's `len` Function

The `len` function takes a collection as an argument and returns the number of elements within the collection. In our case, we provide a tuple (the collection), and the function will count the total number of items (elements) in the tuple and return the value. Below is an example of finding the number of integers in a tuple.

my_tuple = (1, 2, 3, 4, 5)
length = len(my_tuple)
print(length)

# Output: 5

Using Python's `count` Method

The `count` method returns the total number of occurrences of a specified item within a collection. In our case, the collection is a tuple but could just as easily be a list, set, or string. Below is an example of finding the total number of 1s in a tuple.

my_tuple = (1, 2, 1, 1, 4, 3, 3, 2, 3, 2, 1)
total = my_tuple.count(1)
print(total)

# Output: 4

Using Python's `index` Method

The `index` method returns the starting index of the first occurrence of the specified item. Below is an example of finding the first occurrence of the number 3 in a tuple.

my_tuple = (1, 2, 1, 1, 4, 3, 3, 2, 3, 2, 1)
index = my_tuple.index(3)
print(index)

# Output: 5












39 views0 comments
bottom of page