Tutorial

Tuples in Python

7 min read

Python offers a wide range of data structures to work with. One of these structures is the tuple. Tuples in Python is an ordered, immutable sequence of elements.

In Python, tuples are similar to lists, but unlike lists, they cannot be modified once they are created.

This makes tuples useful for storing data that should not be changed, such as the dimensions of an image or the name and address of a person.

Tuples are also commonly used in Python for returning multiple values from a function.

They can be accessed using indexing, slicing, and other built-in methods, just like lists. However, because tuples are immutable, they are generally more efficient than lists in certain situations.

In this article, we will explore tuples in Python, including how to create and manipulate them, and how they differ from other data structures. We will also examine some use cases for Python tuples. For example, working with multiple return values from a function or creating a set of values that should not be modified.

Create and Access Elements of a Tuple in Python

In Python, a tuple is created by enclosing a sequence of values inside parentheses. Here is an example:

# create a tuple
my_tuple = (1, 2, 3, 'four', 'five')

# access elements of the tuple using indexing
print(my_tuple[0])   # prints 1
print(my_tuple[3])   # prints 'four'

# access elements of the tuple using negative indexing
print(my_tuple[-1])  # prints 'five'
print(my_tuple[-2])  # prints 'four'

Here, we created a tuple called my_tuple containing five elements: three integers and two strings. We accessed individual elements of the tuple using indexing. The first element of the tuple has an index of 0, and the last element has an index of -1.

We can also use slicing to access a range of elements in a tuple. Here is an example:

# access a range of elements using slicing
print(my_tuple[1:3])     # prints (2, 3)
print(my_tuple[:3])      # prints (1, 2, 3)
print(my_tuple[3:])      # prints ('four', 'five')
print(my_tuple[1:-1])    # prints (2, 3, 'four')

Here, we used slicing to access a range of elements in the tuple. The first argument of the slice is the starting index, and the second argument is the ending index (not inclusive). If the first argument is not specified, it defaults to 0. If the second argument is not specified, it defaults to the length of the tuple.

Tuples in Python are immutable, which means that we cannot modify individual elements of the tuple once it is created. However, we can create a new tuple that contains some or all of the elements of the original tuple. Here is an example:

# create a new tuple from an existing tuple
new_tuple = my_tuple[:2] + ('two and a half',) + my_tuple[2:]
print(new_tuple)    # prints (1, 2, 'two and a half', 3, 'four', 'five')

Here, we created a new tuple called new_tuple by concatenating a slice of the original tuple, a single-element tuple containing the string ‘two and a half’, and another slice of the original tuple. We used the + operator to concatenate the tuples, and we used the comma at the end of the single-element tuple to indicate that it is a tuple (otherwise it would be interpreted as a string).

Add and Remove Elements from Tuple in Python

In Python, tuples are immutable, which means that we cannot add or remove elements from an existing tuple directly.

However, we can create a new tuple that contains some or all of the elements of the original tuple, along with any new elements that we want to add.

Here is an example of adding elements to a tuple in Python:

# create a tuple
my_tuple = (1, 2, 3, 'four', 'five')

# add elements to the tuple
new_tuple = my_tuple + ('six', 'seven')
print(new_tuple)    # prints (1, 2, 3, 'four', 'five', 'six', 'seven')

Here, we created a new tuple called new_tuple by concatenating the original tuple with a tuple containing two new elements (‘six’ and ‘seven’). We used the + operator to concatenate the tuples.

To remove elements from a tuple, we can create a new tuple that contains only the elements that we want to keep. Here is an example:

# create a tuple
my_tuple = (1, 2, 3, 'four', 'five')

# remove an element from the tuple
new_tuple = my_tuple[:3] + my_tuple[4:]
print(new_tuple)    # prints (1, 2, 3, 'five')

Here, we created a new tuple called new_tuple by concatenating a slice of the original tuple that contains the first three elements, with a slice of the original tuple that contains the element at index 4 (the fifth element) and all the elements after it. This effectively removes the element at index 3 (the fourth element) from the tuple.

Note: When we add or remove elements from a tuple, we are actually creating a new tuple object in memory. This can be inefficient if we need to modify a tuple frequently, in which case it might be better to use a list instead. However, tuples have other advantages, such as being more memory-efficient than lists and being hashable (which means they can be used as keys in dictionaries).

Methods of Tuple in Python

In Python, as we know tuples are immutable. As a result, the methods available for tuples are limited compared to other data types like lists.

Here are the methods available for tuples in Python:

  • count(x) – This method returns the number of times a given element x appears in the tuple.
my_tuple = (1, 2, 3, 4, 4, 5, 4)
count_of_4 = my_tuple.count(4)
print(count_of_4)    # prints 3
  • index(x) – This method returns the index of the first occurrence of a given element x in the tuple.
my_tuple = (1, 2, 3, 4, 4, 5, 4)
index_of_4 = my_tuple.index(4)
print(index_of_4)    # prints 3

Note: Both of these methods return values but do not modify the original tuple. Since tuples are immutable, we cannot modify them in place.

Advantages of Tuple over Lists in Python

In Python, both tuples and lists are used to store collections of elements.

However, tuples and lists have some differences that make them suitable for different use cases.

Here are some advantages of tuples over lists in Python:

  • Immutability – Tuples are immutable, which means that once they are created, their elements cannot be modified. This makes tuples useful for situations where we want to ensure that the elements in a collection cannot be changed accidentally. For example, if we have a function that returns multiple values, we can use a tuple to return those values and ensure that they cannot be modified by the caller.
  • Performance – Tuples are generally faster than lists for certain operations, such as iterating over the elements, indexing, and unpacking. This is because tuples are implemented as a contiguous block of memory, whereas lists are implemented as an array of pointers to the elements. Since tuples are immutable, their memory allocation can be optimized by the interpreter, which can lead to better performance.
  • Hashability – Tuples are hashable, which means that they can be used as keys in dictionaries and elements in sets. This is because the hash value of a tuple is based on the hash values of its elements, and since tuples are immutable, their hash values do not change. Lists, on the other hand, are not hashable, since they are mutable and their hash values can change if their elements are modified.
  • Syntax – Tuples have a simple and concise syntax, which can make code more readable and easier to write. For example, we can create a tuple using parentheses without needing to use commas between the elements. This can be particularly useful when we need to create a small collection of elements on the fly.

Conclusion

In Python, tuples are an important data structure for storing collections of elements.

They are similar to lists in many ways but have some key differences that make them useful for certain use cases. Tuples are immutable, meaning that once they are created, their elements cannot be modified.

This makes tuples useful for situations where we want to ensure that the elements in a collection cannot be changed accidentally. Additionally, tuples are generally faster than lists for certain operations, such as iterating over the elements and indexing.

They are also hashable, meaning that they can be used as keys in dictionaries and elements in sets.

Finally, tuples have a simple and concise syntax that can make code more readable and easier to write.

It’s important to keep in mind that tuples are not designed for frequent modification. If we need to modify a collection of elements frequently, consider using a list instead.

However, if we need to store a collection of elements that will not change and that we may need to use as keys in dictionaries or elements in sets, tuples are a good choice.

Do you know our Python tutors are dedicated to providing the best possible learning experience?