Data Structures: Tuples

In this chapter, we will learn about tuples, an ordered collection of items in Python.

ℹ️
Tuples are similar to lists, but with one key difference: they are immutable, meaning their elements cannot be changed after creation.

Tuples are commonly used to store related pieces of information together.

Creating Tuples

In Python, tuples are created by placing a sequence of comma-separated values inside parentheses (). Here is an example of a simple tuple:

tuple_example.py
# Create a tuple of integers
numbers = (1, 2, 3, 4, 5)
print(numbers)

In this example, we create a tuple called numbers containing five integers. Tuples can contain elements of any data type, including numbers, strings, and even other tuples.

Accessing Tuple Elements

You can access individual elements of a tuple using their index, just like with lists. The index of the first element in a tuple is 0, the second element is 1, and so on. Negative indices can also be used to access elements from the end of the tuple.

Here is an example of accessing tuple elements:

tuple_access.py
numbers = (1, 2, 3, 4, 5)

# Access the first element
print(numbers[0])
# Output: 1

# Access the second element
print(numbers[1])
# Output: 2

# Access the last element
print(numbers[-1])
# Output: 5

In this example, we access the first element of the numbers tuple using the index 0, second element using index 1 and the last element using the index -1.

Tuple Operations

While tuples are immutable, they still support a variety of operations. Here are some common tuple operations:

Tuples support a variety of operations, including concatenation, repetition, membership testing, and more. Here are some common tuple operations:

OperationDescription
+Concatenation: Combines two or more tuples to create a new tuple.
*Repetition: Creates a new tuple by repeating the elements of an existing tuple.
inMembership: Checks if an element is present in a tuple.
len()Length: Returns the number of elements in a tuple.
SlicingExtracts a subset of elements from a tuple.
UnpackingAssigns the elements of a tuple to multiple variables in a single line.
()Empty tuple: Creates an empty tuple.
  • Concatenation: You can combine two or more tuples to create a new tuple.
tuple_concatenation.py
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
result = tuple1 + tuple2
print(result)
  • Repetition: You can create a new tuple by repeating the elements of an existing tuple.
tuple_repetition.py
tuple1 = ('a', 'b')
result = tuple1 * 3
print(result)
  • Membership: You can check if an element is present in a tuple using the in operator.
tuple_membership.py
  numbers = (1, 2, 3, 4, 5)
  print(3 in numbers)  # Output: True
  print(6 in numbers)  # Output: False
  • Length: You can find the number of elements in a tuple using the len() function.
tuple_length.py
  numbers = (1, 2, 3, 4, 5)
  print(len(numbers))  # Output: 5
  • Slicing: You can extract a subset of elements from a tuple using slicing.
tuple_slicing.py
  numbers = (1, 2, 3, 4, 5)
  print(numbers[1:4])  # Output: (2, 3, 4)
  • Unpacking: You can assign the elements of a tuple to multiple variables in a single line.
tuple_unpacking.py
  numbers = (1, 2, 3)
  a, b, c = numbers
  print(a, b, c)  # Output: 1 2 3

Immutable Nature of Tuples

One of the key features of tuples is their immutability. Once a tuple is created, its elements cannot be changed. This means you cannot modify, add, or remove elements from a tuple after it has been created.

tuple_immutable.py
numbers = (1, 2, 3, 4, 5)

# Attempt to change the first element
numbers[0] = 10  # Raises a TypeError

Key Points

  • Tuples are ordered collections of items in Python.
  • Tuples are created by placing a sequence of comma-separated values inside parentheses ().
  • Tuples are immutable, meaning their elements cannot be changed after creation.
  • Tuples support a variety of operations, including concatenation, repetition, membership testing, and more.

Exercise

  1. Create a tuple called colors containing the names of different colors.
  2. Print the second element of the colors tuple.
  3. Check if the color ‘red’ is present in the colors tuple.
  4. Find the number of colors in the colors tuple.

Summary

In this example, we attempt to change the value of the first element of the numbers tuple, which raises a TypeError because tuples are immutable. This is a key difference between tuples and lists in Python.

Tuples are often used to represent fixed collections of data that should not be modified, such as the dimensions of a rectangle or the coordinates of a point in a 2D space. They are also used to return multiple values from a function, as we will see in later chapters.