4.2 Tuples: Immutable Sequences

Tuples in Python are very similar to lists but with one key difference: tuples are immutable, meaning that once they are created, their elements cannot be changed, added, or removed. Tuples are useful when you want to ensure that a sequence of values remains constant throughout the program.

In this section, we will explore how to create tuples, access their elements, perform operations on them, and understand their immutability.


4.2.1 Creating Tuples

Tuples are created by placing elements inside parentheses () and separating them with commas. Tuples can hold any data type, including numbers, strings, lists, and even other tuples.

Syntax:

my_tuple = (element1, element2, element3, ...)

Examples:

An empty tuple:

empty_tuple = ()

A single element tuple (note the comma is required to distinguish it from a regular value):

single_element_tuple = (1,)  # Output: (1,)

A tuple without parentheses (Python allows this in certain cases):

implicit_tuple = 1, 2, 3

A tuple of tuples (nested tuple):

nested_tuple = ((1, 2), (3, 4), (5, 6))

A tuple of mixed types:

mixed_tuple = (1, "hello", 3.14, True)

A tuple of integers:

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

4.2.2 Accessing Tuple Elements

You can access elements in a tuple using indexing just like lists. Python uses zero-based indexing, where the first element is at index 0. Negative indexing allows you to access elements from the end of the tuple.

Syntax:

tuple_name[index]

Examples:

Accessing elements in a nested tuple:

nested_tuple = ((1, 2), (3, 4), (5, 6))
print(nested_tuple[1][1])  # Output: 4 (second element of the second tuple)

Accessing elements using negative indexing:

print(fruits[-1])  # Output: cherry
print(fruits[-2])  # Output: banana

Accessing elements by index:

fruits = ("apple", "banana", "cherry")
print(fruits[0])  # Output: apple
print(fruits[2])  # Output: cherry

4.2.3 Slicing Tuples

Just like lists, tuples support slicing, which allows you to access a range of elements. The slicing syntax is the same as that for lists: tuple[start:end], where start is the index of the first element to include and end is the index of the element to exclude.

Syntax:

tuple_name[start:end]
tuple_name[start:end:step]

Examples:

Using a step size:

print(fruits[::2])  # Output: ('apple', 'cherry', 'fig')

Omitting start or end:

print(fruits[:3])  # Output: ('apple', 'banana', 'cherry')
print(fruits[2:])  # Output: ('cherry', 'date', 'fig')

Slicing a tuple:

fruits = ("apple", "banana", "cherry", "date", "fig")
print(fruits[1:4])  # Output: ('banana', 'cherry', 'date')

4.2.4 Immutability of Tuples

Tuples are immutable, meaning once they are created, their contents cannot be changed. This immutability makes tuples a good choice for storing data that should not be modified during the execution of a program.

Examples:

  1. Tuples do not have methods like append(), remove(), or pop() because their contents cannot be altered.

Attempting to change a tuple’s element results in an error:

my_tuple = (1, 2, 3)
my_tuple[1] = 10  # Raises TypeError: 'tuple' object does not support item assignment

4.2.5 Operations on Tuples

While you cannot change the elements of a tuple, there are still several operations you can perform on tuples.

4.2.5.1 Concatenation

You can concatenate two or more tuples using the + operator, which creates a new tuple by combining the two.

Example:

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple)  # Output: (1, 2, 3, 4, 5, 6)

4.2.5.2 Repetition

You can repeat a tuple multiple times using the * operator.

Example:

repeated_tuple = (1, 2, 3) * 3
print(repeated_tuple)  # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

4.2.5.3 Membership Testing

You can check whether an item exists in a tuple using the in and not in operators.

Example:

fruits = ("apple", "banana", "cherry")
print("banana" in fruits)  # Output: True
print("grape" not in fruits)  # Output: True

4.2.5.4 Tuple Length

You can determine the number of elements in a tuple using the len() function.

Example:

fruits = ("apple", "banana", "cherry")
print(len(fruits))  # Output: 3

4.2.5.5 Tuple Methods

Tuples have two methods:

index(): Returns the index of the first occurrence of a specified value.
Example:

numbers = (1, 2, 3, 4, 5)
print(numbers.index(3))  # Output: 2

count(): Returns the number of times a specified value appears in a tuple.
Example:

numbers = (1, 2, 3, 2, 2, 4)
print(numbers.count(2))  # Output: 3

4.2.6 Unpacking Tuples

You can unpack tuples, which means assigning the elements of a tuple to individual variables. This is a convenient way to assign multiple values at once.

Syntax:

variable1, variable2, ... = tuple_name

Examples:

Unpacking with fewer variables (using * to capture the remaining elements):

my_tuple = (1, 2, 3, 4, 5)
a, *b, c = my_tuple
print(a)  # Output: 1
print(b)  # Output: [2, 3, 4]
print(c)  # Output: 5

Basic tuple unpacking:

my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c)  # Output: 1 2 3

4.2.7 Converting Between Lists and Tuples

You can easily convert between lists and tuples using the list() and tuple() functions. This is useful when you need to modify a tuple temporarily by converting it to a list, making the changes, and then converting it back to a tuple.

Examples:

List to Tuple:

my_list = [4, 5, 6]
my_tuple = tuple(my_list)
print(my_tuple)  # Output: (4, 5, 6)

Tuple to List:

my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list)  # Output: [1, 2, 3]

4.2.8 Use Cases for Tuples

  1. Storing Heterogeneous Data

Returning Multiple Values from a Function:
Tuples are often used to return multiple values from a function.Example:

def get_coordinates():
    return (10, 20)

x, y = get_coordinates()
print(x, y)  # Output: 10 20

:
Tuples are ideal for grouping different types of data that logically belong together and should not be modified.

Example:

person = ("Alice", 30, "Engineer")

Using Tuples as Dictionary Keys:
Since tuples are immutable, they can be used as keys in dictionaries, unlike lists.Example:

coordinates = {(0, 0): "origin", (1, 2): "point A"}
print(coordinates[(1, 2)])  # Output: point A

4.2.9 Summary

  • Tuples are immutable sequences, meaning their contents cannot be changed after creation.
  • You can create tuples using parentheses () and access elements using indexing and slicing.
  • While tuples are immutable, you can still perform various operations such as concatenation, repetition, and membership testing.
  • Tuples support unpacking, which allows you to assign tuple elements to individual variables.
  • You can convert between lists and tuples using the list() and tuple() functions.
  • Tuples are often used when immutability is desired or when storing fixed collections of heterogeneous data.

Understanding how to use tuples is essential for writing robust Python programs, especially when you need to handle immutable sequences of data or return multiple values from functions.