Back to articles list Articles
8 minutes read

Basics of Python: Tuple Examples

What is a tuple in Python? Explore this data type, learn how it’s different from Python’s other data types, and discover use cases and tuple examples.

A tuple is one of Python’s built-in data structures. Its unique features make tuples widely used for certain tasks. To use tuples for the right task, you need to know what they are and how to perform operations on them. In short, you need examples of Python tuples. That’s exactly what we’ll cover in this article.

If you’re new to programming, I suggest learning Python’s basics before studying its data structures. It won’t take you a long time to learn Python, but you need a carefully structured plan. Once you learn the basics and do some practice, it’ll be much easier to learn tuples or other data structures. You can start with our three-course Python Basics track, which offers the opportunity to practice while learning Python basics. It contains 259 coding challenges.

If you feel like you’re ready to learn tuples, let’s move on.

What Is a Tuple in Python?

A tuple is a collection of values separated by a comma and enclosed in parentheses. Here is a Python tuple example:

>>> # creating a tuple
>>> my_tuple = (1, 2, 3)
<class 'tuple'>

Tuples can store values of different data types. In the following example, we see an integer, string, and a Boolean value stored in the same tuple:

>>> # creating a tuple with different types of data
>>> my_tuple = (1, "John", True)
>>> print(type(my_tuple))
<class 'tuple'>

We can also create tuples using the tuple() constructor on iterables. The following example is a Python tuple created from a string:

>>> my_tuple = tuple("Python")
>>> print(my_tuple)
('P', 'y', 't', 'h', 'o', 'n')

How Is a Tuple Different From Other Data Structures?

Python’s four main built-in data structures are dictionary, list, tuple, and set. Although there are some common features among them, each data structure is unique and serves specific purposes. It’s of crucial importance to know the differences and similarities among Python data structures. Otherwise, you may end up choosing the wrong data structure for the task, which will cost you unnecessary time and computation.

You’ll often see comparisons between built-in data structures, e.g. tuple vs. list and tuple vs. set. Let’s briefly mention some differences among these data structures.

  • Tuples and lists are quite similar in terms of their structure and the operations you can do on them. However – unlike lists – tuples are immutable, or unchangeable. We’ll explain this in the next section.
  • Tuples and lists are ordered collections of items, which means you can access an item (or multiple items) using index values. On the other hand, sets are an unordered collection of items; the order of items in a set changes each time you use it.
  • Both tuples and lists can contain duplicate items, whereas sets cannot. All items in a set are unique.
  • You can append, update, and delete elements of a list. You cannot do such operations with tuples.

Read this article if you’d like to learn more about the difference between lists, sets, and tuples. Also, you may see some of these data structures are used together, such as a list of tuples or a list of lists used as keys of a dictionary.

Tuples Are Immutable

The key characteristic of a tuple is immutability, which means you can’t make changes to a tuple once it’s created. Let’s elaborate on this.

Once you’ve made a tuple, you can’t add new items to it. Thus, tuples don’t have an append() or extend() method. It’s also not possible to remove an item from a tuple. Unlike lists, you can’t apply methods like remove() and pop() to tuples.

Immutability applies to item-level updates as well. You can’t change the value of an item in a tuple. If you try, you’ll get a type error saying that the tuple object does not support item assignment.

To summarize, once you create a tuple, that’s it. You can’t make any modifications to it. All you can do is delete it entirely, which can be done using Python’s del keyword.

Immutability sounds like a shortcoming, but it makes tuples a great choice for certain tasks. Suppose you have a collection of values that should never be changed. If you use a list to store these values, there is a risk that they could be accidentally updated. Tuples are life-savers in those cases; they prevent mistaken changes to your collection of items.

Example Python Tuple Use Case

A typical use case for tuples is functions that return multiple values. In these cases, the returned values are packed in a tuple.

The following function takes a Python dictionary as input and returns the sum of its values and the number of items in it (i.e. its length):

>>> def get_sum_and_count(dct):
>>>     return sum(dct.values()), len(dct)

Let’s create a dictionary and test our function:

>>> names = {"John": 24, "Jane": 22, "Ashley": 33, "Max": 28}
>>> get_sum_and_count(names)
(107, 4)

The output is a tuple of two items: the sum of all values (104) and the number of key-value pairs in the dictionary (4). If we want to assign these values to separate variables, we can do it this way:

>>> value_sum, item_count = get_sum_and_count(names)
>>> print(value_sum)
107
>>> print(item_count)
4

The code snippet above assigns the output of the get_sum_and_count function to two different variables called value_sum and item_count. This separate item assignment is also known as tuple unpacking.

Operations on Tuples

To use a data structure efficiently, you need to know how to interact with it and what operations you can perform on it. Let’s go over some examples of operations on tuples.

Indexing and slicing

Item indexes can be used for extracting one or more items from a tuple. In Python, an index starts from 0 and increments by 1. (This is also true for lists.) Here is an example:

>>> my_tuple = (12, 23, 51, 34, 72, 66)
>>> # get the first item
>>> my_tuple[0]
12
>>> # get the third item
>>> my_tuple[2]
51

You can also indicate an index's position from the end of the tuple. In that case, the index of the last item is -1, the index of the next-to-last item is -2, and so on. The following code extracts the last item in a tuple:

>>> my_tuple = (12, 23, 51, 34, 72, 66)
>>> # get the last item
>>> my_tuple[-1]
66

To extract multiple items, we can use slicing based on index values. The syntax is simple: put the starting index, a colon, and the ending index and wrap the whole thing in square brackets. Here’s an example, followed by an explanation:

>>> my_tuple = (12, 23, 51, 34, 72, 66)
>>> # get the first three items
>>> my_tuple[0:3]
(12,  23, 51)

The first value inside the square brackets is the starting index (in this case, the beginning of the tuple, or 0). The second one is the index of the last item (3).

Note that the upper bound (i.e. the ending index) is exclusive – it’s not included in the results. So, the slice [0:3] includes the first three items in the tuple – the ones with index values 0, 1, and 2.

If you want to start from the beginning of the tuple, you don’t have to specify the starting index; [:3] is the same as [0:3]. Similarly, if you want the slice to go until the last item in the tuple, you can leave the ending index blank. If you wanted everything from index 5 to the end of the tuple, you’d write [5:].

Another slicing parameter is the step size. By default, every item within the slice is extracted (i.e. step size is 1). We can change this behavior by increasing the step size. For instance, a step size of 2 gives us every other item within the slice:

>>> my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>> # get every other item between the first and sixth items
>>> my_tuple[0:6:2]
(1,  3,  5)

Checking Items in a Tuple

One of the most frequent operations on a data structure is checking if an item exists in it. For tuples, you can use the in operator for this task. It returns a Boolean value of True if the item exists in the tuple. Here’s an example of a Python tuple and the in operator:

>>> my_tuple = ("Jane", "John", "Emily", "Matt")
>>> "Jane" in my_tuple
True

Another option is to use the count() method, which returns the number of occurrences of the item. If it returns 0, then the item does not exist in the tuple:

>>> my_tuple = ("Jane", "John", "Emily", "Matt")
>>> my_tuple.count("Jane")
1
>>> my_tuple.count("Alex")
0

If you’re only interested in if the item exists in the tuple (instead of how often that item occurs), I suggest using the in operator. With the in operator, the execution stops once the item is found. On the other hand, the count() method goes through the entire tuple to find all occurrences, which can be redundant computation.

To count all the items in a tuple (i.e. find the length of a tuple), we can use Python’s built-in len() function:

>>> my_tuple = ("Jane", "John", "Emily", "Matt")
>>> len(my_tuple)
4

Adding tuples together

You can add multiple tuples together using the + operator. It creates a new tuple that contains all the items from both tuples.

>>> my_tuple = (1, 5, 10)
>>> new_tuple = (20, 25, 30)
>>> my_tuple + new_tuple
(1, 5, 10, 20, 25, 30)

Going Beyond Python Tuple Examples

Tuples are an essential Python data structure. We hope these Python tuple examples and explanations helped you understand them.

If you want to write well-organized and efficient software programs, you need to have a comprehensive understanding of data structures and how to use them. Python’s role in Big Data depends on how you leverage data structures. To learn more – and get some hands-on experience working with tuples and other data structures – our Python Data Structures in Practice course will help you master this topic.