Use Tuples in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will gain a comprehensive understanding of tuples in Python. You will learn how to create tuples, access their elements using indexing and slicing, and explore their immutable nature. You will also practice using tuple operators, unpacking, and common built-in functions to efficiently work with tuple data.

Create and Access Tuples

In this step, you will learn how to create tuples and access their elements. Tuples are ordered, immutable collections of items, meaning their contents cannot be changed after creation.

First, locate the file explorer on the left side of the WebIDE. Find and open the file named tuple_basics.py. We will write our code in this file.

Let's start by creating a few different types of tuples. Add the following code to tuple_basics.py:

## Create an empty tuple
empty_tuple = ()
print("Empty tuple:", empty_tuple)
print("Type of empty_tuple:", type(empty_tuple))

## Create a tuple with a single element (note the trailing comma)
single_element_tuple = (50,)
print("\nSingle element tuple:", single_element_tuple)
print("Type of single_element_tuple:", type(single_element_tuple))

## Create a tuple with multiple elements
fruits = ("apple", "banana", "cherry")
print("\nFruits tuple:", fruits)

## Create a tuple from a list using the tuple() constructor
numbers_list = [1, 2, 3, 4]
numbers_tuple = tuple(numbers_list)
print("\nTuple from list:", numbers_tuple)

After adding the code, save the file (you can use the Ctrl+S shortcut). Then, open the terminal at the bottom of the WebIDE and run the script with the following command:

python tuple_basics.py

You should see the following output, which confirms the creation and types of your tuples:

Empty tuple: ()
Type of empty_tuple: <class 'tuple'>

Single element tuple: (50,)
Type of single_element_tuple: <class 'tuple'>

Fruits tuple: ('apple', 'banana', 'cherry')

Tuple from list: (1, 2, 3, 4)

Now, let's learn how to access the elements within a tuple. You can use indexing (starting from 0) to get a single element and slicing to get a sub-sequence of elements.

Add the following code to the end of your tuple_basics.py file:

## Define a sample tuple for accessing elements
my_tuple = ('p', 'y', 't', 'h', 'o', 'n')
print("\nOriginal tuple:", my_tuple)

## Access elements using indexing
print("First element (index 0):", my_tuple[0])
print("Last element (index -1):", my_tuple[-1])

## Access elements using slicing
print("Elements from index 1 to 3:", my_tuple[1:4])
print("Elements from index 2 to the end:", my_tuple[2:])
print("Reverse the tuple:", my_tuple[::-1])

Save the file again and run the script from the terminal:

python tuple_basics.py

The complete output will now include the results of accessing the tuple elements:

Empty tuple: ()
Type of empty_tuple: <class 'tuple'>

Single element tuple: (50,)
Type of single_element_tuple: <class 'tuple'>

Fruits tuple: ('apple', 'banana', 'cherry')

Tuple from list: (1, 2, 3, 4)

Original tuple: ('p', 'y', 't', 'h', 'o', 'n')
First element (index 0): p
Last element (index -1): n
Elements from index 1 to 3: ('y', 't', 'h')
Elements from index 2 to the end: ('t', 'h', 'o', 'n')
Reverse the tuple: ('n', 'o', 'h', 't', 'y', 'p')

You have now successfully created tuples and accessed their elements.

Understand Tuple Immutability

A key characteristic of tuples is their immutability. This means that once a tuple is created, you cannot change, add, or remove its elements. In this step, you will see what happens when you try to modify a tuple and learn the correct way to achieve a "modification" by creating a new tuple.

Open the file tuple_modification.py from the file explorer.

First, let's try to change an element in a tuple directly. Add the following code to tuple_modification.py. The line that attempts the modification is commented out.

my_tuple = ('a', 'b', 'c', 'd', 'e')
print("Original tuple:", my_tuple)

## The following line will cause a TypeError because tuples are immutable.
## You can uncomment it to see the error for yourself.
## my_tuple[0] = 'f'

If you were to run the code with the second-to-last line uncommented, Python would stop and show a TypeError: 'tuple' object does not support item assignment.

Since we cannot modify a tuple in place, the solution is to create a new tuple with the desired changes. We can do this using slicing and concatenation (+).

Add the following code to the end of tuple_modification.py to see how to "replace" an element:

## "Modify" a tuple by creating a new one
## Concatenate a new single-element tuple ('f',) with a slice of the original tuple
modified_tuple = ('f',) + my_tuple[1:]

print("New 'modified' tuple:", modified_tuple)
print("Original tuple is unchanged:", my_tuple)

Similarly, you can "delete" an element by creating a new tuple that excludes it. Add this code to your file:

## "Delete" an element by creating a new tuple
## Concatenate the slice before the element with the slice after the element
tuple_after_deletion = my_tuple[:2] + my_tuple[3:] ## Excludes element at index 2 ('c')

print("\nNew tuple after 'deletion':", tuple_after_deletion)

Save the file and run it from the terminal:

python tuple_modification.py

The output will demonstrate that we have created new tuples while the original remains untouched:

Original tuple: ('a', 'b', 'c', 'd', 'e')
New 'modified' tuple: ('f', 'b', 'c', 'd', 'e')
Original tuple is unchanged: ('a', 'b', 'c', 'd', 'e')

New tuple after 'deletion': ('a', 'b', 'd', 'e')

This step highlights the immutable nature of tuples and the standard practice for working around this limitation.

Use Tuple Operators and Unpacking

Python provides several useful operators for working with tuples. You will also learn about tuple unpacking, a powerful feature for assigning tuple elements to variables.

Open the file tuple_operators.py from the file explorer.

Let's explore the concatenation (+), repetition (*), and membership (in) operators. Add the following code to tuple_operators.py:

tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')

## Concatenation (+)
concatenated_tuple = tuple1 + tuple2
print("Concatenated:", concatenated_tuple)

## Repetition (*)
repeated_tuple = tuple1 * 3
print("Repeated:", repeated_tuple)

## Membership (in)
is_present = 'b' in tuple2
print("\nIs 'b' in tuple2?", is_present)

is_absent = 5 in tuple1
print("Is 5 in tuple1?", is_absent)

Save the file and run it from the terminal:

python tuple_operators.py

You will see the results of these operations:

Concatenated: (1, 2, 3, 'a', 'b', 'c')
Repeated: (1, 2, 3, 1, 2, 3, 1, 2, 3)

Is 'b' in tuple2? True
Is 5 in tuple1? False

Next, let's explore tuple unpacking. This allows you to assign the elements of a tuple to multiple variables in a single, readable line. The number of variables must match the number of elements in the tuple.

Add the following code to the end of tuple_operators.py:

## Tuple unpacking
person_info = ("Alice", 30, "Engineer")
name, age, profession = person_info

print("\nOriginal info tuple:", person_info)
print("Unpacked Name:", name)
print("Unpacked Age:", age)
print("Unpacked Profession:", profession)

Save the file again and run the script:

python tuple_operators.py

The output will now include the unpacked variables:

Concatenated: (1, 2, 3, 'a', 'b', 'c')
Repeated: (1, 2, 3, 1, 2, 3, 1, 2, 3)

Is 'b' in tuple2? True
Is 5 in tuple1? False

Original info tuple: ('Alice', 30, 'Engineer')
Unpacked Name: Alice
Unpacked Age: 30
Unpacked Profession: Engineer

Tuple unpacking is especially useful for functions that return multiple values, as they often return them in a tuple.

Apply Built-in Functions and Methods

In this final step, you will learn to use common built-in functions and methods that operate on tuples. Tuples have two primary methods, count() and index(), and can be used with many general-purpose functions.

Open the file tuple_functions.py from the file explorer.

Let's start with the tuple methods. count() returns the number of times an element appears, and index() returns the index of the first occurrence of an element.

Add the following code to tuple_functions.py:

my_tuple = (1, 5, 2, 8, 5, 3, 5, 9)
print("Tuple:", my_tuple)

## count() method
count_of_5 = my_tuple.count(5)
print("Count of 5:", count_of_5)

## index() method
index_of_8 = my_tuple.index(8)
print("Index of 8:", index_of_8)

Now, let's use some built-in functions that are very useful with tuples, such as len(), max(), min(), sum(), and sorted().

Add the following code to the end of tuple_functions.py:

number_tuple = (10, 5, 20, 15, 30, 5)
print("\nNumber tuple:", number_tuple)

## len() function
print("Length:", len(number_tuple))

## max() and min() functions
print("Maximum value:", max(number_tuple))
print("Minimum value:", min(number_tuple))

## sum() function (for numeric tuples)
print("Sum of elements:", sum(number_tuple))

## sorted() function (returns a new sorted list)
sorted_list = sorted(number_tuple)
print("Sorted list from tuple:", sorted_list)

Note that the sorted() function returns a new list, not a tuple. If you need a sorted tuple, you can convert the result back using tuple(sorted_list).

Save the file and run it from the terminal:

python tuple_functions.py

Your output should look like this:

Tuple: (1, 5, 2, 8, 5, 3, 5, 9)
Count of 5: 3
Index of 8: 3

Number tuple: (10, 5, 20, 15, 30, 5)
Length: 6
Maximum value: 30
Minimum value: 5
Sum of elements: 85
Sorted list from tuple: [5, 5, 10, 15, 20, 30]

You have now learned to use important methods and functions to inspect and analyze tuples.

Summary

In this lab, you have gained a solid foundation in using Python tuples. You learned how to create tuples in various ways and how to access their elements using indexing and slicing. You explored the core concept of tuple immutability and practiced creating new tuples to perform "modifications". You also became familiar with common tuple operators like + and *, the convenience of tuple unpacking, and the utility of built-in methods (count(), index()) and functions (len(), max(), sorted()) for working with tuple data.