Working with Tuples in Python

Andrei Maksimov

Andrei Maksimov

5
(2)

A tuple is a collection of ordered and immutable objects. Python tuples are sequences, just like lists. The differences between tuples and lists are: the tuples cannot be changed, and they are faster and memory-efficient in compression with lists. Tuples are commonly used in parallel processing, Big Data, Machine Learning, and relational DB data management tasks. In this tutorial, we will cover the tuples in detail and describe their purpose by providing examples to demonstrate how you can use them in real life.

Tuples

In general, tuples, while useful for quick and dirty data composition and in many cases they should be replaced with named tuples, dataclasses, or regular classes.

Tuple vs List

Tuples are the fastest data type to instantiate, particularly in the case of tuple literals:

python3 -m timeit '(1,2,3)'
50000000 loops, best of 5: 6.48 nsec per loop

python3 -m timeit '[1,2,3]'
5000000 loops, best of 5: 44.4 nsec per loop

On my machine, it’s more than 7 times faster.

Tuples are always compared to lists, so here are the major differences:

  • Tuples are fixed-length sequences of heterogeneous data (stores elements of different types)
  • Lists are for arbitrary-length sequences of homogeneous data (stores data of the same type)

The best way to think about tuples is that lists are like the columns in a spreadsheet, and tuples are rows:

Working with Tuples in Python - Tuple vs List

Creating a tuple

Let’s take a look at how you can create a tuple:

# Empty tuple
record = ()
print(record)

# Tuple with mixed datatypes
record = (2, "John", "Doe", "Sales")
print(record)
1. Working with Tuples in Python - Creating tuple

We’ve created an empty tuple and tuple of mixed data types (int and str).

Packing and unpacking tuples

A tuple can be created without using parentheses.

This operation is known as tuple packing:

record = 2, "John", "Doe", "Sales"

print(record)

Wise versa, you can extract tuple values back into variables. This operation is called unpacking a tuple:

rec_id, rec_first, rec_last, rec_dep = record

print(f'ID: {rec_id}')
print(f'First name: {rec_first}')
print(f'Last name: {rec_last}')
print(f'Department: {rec_dep}')
2. Working with Tuples in Python - Packing and unpacking

Note:

  • During tuple unpacking operation, the number of variables on left-hand side should be equal to number of values in a given tuple.
  • If you’d like to skip some of tuple elements, you may use _ (underline character) instead of providing a variable.
  • In addition to that *args syntax (arbitrary variables number) is also available.
record = (2, "John", "Doe", "Sales")

# Skipping tuple element during unpacking
_, rec_first, rec_last, rec_dep = record

print(f'First name: {rec_first}')
print(f'Last name: {rec_last}')
print(f'Department: {rec_dep}')

print()

# Using arbitrary argument list during unpacking
rec_id, *args, rec_dep = record

print(f'ID: {rec_id}')
print(f'Department: {rec_dep}')

for arg in args:
    print(f'arg = {arg}')
3. Working with Tuples in Python - Unpacking skipping elements

Accessing tuple elements

Now it’s time to take a look, how we can get access to the tuple elements.

We have several different options:

  • Using element index
  • Using slicing operations

Accessing by index

You can use the index operator [] to access every item in a tuple, where the index starts from 0:

Working with Tuples in Python - Indexing

Note: trying to access an index outside of the tuple index range(in our case 5, 6, etc.) will raise an IndexError Python exception.

record = (2, "John", "Doe", "Sales")

rec_id = record[0]
rec_first = record[1]

print(f'ID: {rec_id}')
print(f'First name: {rec_first}')

print()

rec_last = record[-2]
rec_dep = record[-1]

print(f'Last name: {rec_last}')
print(f'Department: {rec_dep}')
4. Working with Tuples in Python - Accessing by index

Tuple slicing

We can access the range of items in a tuple by using the slicing operator : (colon):

record = (2, "John", "Doe", "Sales")

# Elements from beginning to end
print(record[:])

# Elements from 2nd to 3rd
print(record[1:3])

# Elements from beginning to 2nd
print(record[:-2])

# Elements from 3rd to end
print(record[2:])
5. Working with Tuples in Python - Slicing

Other tuple operations

Modifying tuple values

As soon as a tuple is immutable, you can’t modify its values directly, but you can convert it to the list to make required changes:

record = (2, "John", "Doe", "Sales")

print(f'Original tuple: {record}')

record_list = list(record)
record_list[1] = 'Jane'
record = tuple(record_list)

print(f'Modified tuple: {record}')
6. Working with Tuples in Python - Modifying tuple

Deleting tuple

To delete a tuple completely, you have to use del expression:

record = (2, "John", "Doe", "Sales")

del record

# NameError: name 'record' is not defined
# print(record)
7. Working with Tuples in Python - Deleting tuple

The code block above will delete a variable record referencing a tuple.

Counting tuple elements

To get a number of repeated elements in a tuple, use the following code:

record = (2, "John", "Doe", "Sales", "Sales")

items_count = record.count('Sales')

print(f'Items count: {items_count}')
8. Working with Tuples in Python - Counting tuple elements

Getting tuple element index

Tuple class also provides a convenient method to get element index value:

record = (2, "John", "Doe", "Sales", "Sales")

item_index = record.index('John')

print(f'Item index: {item_index}')
9. Working with Tuples in Python - Getting tuple element index

Check that element exists in tuple

There’re two ways of checking that element exists in a tuple:

  • By using index() method
  • By using in expression

The most straightforward way to do this is to use in expression:

record = (2, "John", "Doe", "Sales")

element = 3
is_found = element in record
print(f'Is {element} found in tuple? => {is_found}')

element = 'John'
is_found = element in record
print(f'Is {element} found in tuple? => {is_found}')
10. Working with Tuples in Python - Tuple membership check

You may use index() tuple method to check element membership in a tuple, but keep in mind that it will generate ValueError: tuple.index(x): x not in tuple exception, if the value not found:

record = (2, "John", "Doe", "Sales")

try:
    element = 'IT'
    item_index = record.index(element)
except ValueError:
    item_index = None
finally:
    if item_index:
        is_found = True
    else:
        is_found = False
    print(f'Is {element} found in tuple? => {is_found}')

We’ll cover Python exception handling in a future article.

Iterating over tuple

We can use for loop to iterate over a tuple:

record = (2, "John", "Doe", "Sales")

for item in record:
    print(f'Item: {item}')
11. Working with Tuples in Python - Iterating over tuple

Named tuples

The major problem with tuples is that it is hard to remember which element has which index.

At this point, many developers start creating a class with read-only properties for storing the data and get access to ut using class.field notation (for example, record.id, record.first_name, etc.).

It’s overkill to use a class for this purpose and Python provides us an elegant solution – named tuples .

Named tuples are easy-to-create and lightweight object types and we can reference their elements using object-like variables or the standard tuple syntax. A named tuple is immutable as a regular tuple, so you can not change its values as soon as you created it.

Creating named tuple

To create a named tuple, we need to import the namedtuple class from the collections module:

from collections import namedtuple

Record = namedtuple('Record', 'id first_name last_name department')
rec = Record(2, "John", "Doe", "Sales")

for item in rec:
    print(f'Item: {item}')

print()

print(f'ID: {rec.id}')
print(f'First name: {rec.first_name}')
print(f'Last name: {rec.last_name}')
print(f'Department: {rec.department}')
12. Working with Tuples in Python - Creating named tuple

How useful was this post?

Click on a star to rate it!

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Top rated Udemy Courses to improve you career

Subscribe to our updates

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Want to be an author of another post?

We’re looking for skilled technical authors for our blog!

Leave a comment

If you’d like to ask a question about the code or piece of configuration, feel free to use https://codeshare.io/ or a similar tool as Facebook comments are breaking code formatting.