A data structure is a particular way of organizing and storing data in a computer so that it can be accessed and modified efficiently. Tuples in Python are an example of a data structure. They are used to store multiple items in a single variable.

Tuples are a fundamental data structure in Python and are particularly useful for storing a sequence of immutable elements.

Introduction to Tuples

Tuples are ordered, meaning the items have a defined order, and immutable, meaning once a tuple is created, its items cannot be changed. This makes tuples particularly useful for storing a collection of data that should not be altered, like the days of the week or coordinates in a plane.

Creating a Tuple

Tuples are defined by enclosing elements in parentheses () and separating them by commas .

Code example:

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

You can also create a tuple without parentheses, by just separating items with commas.

another_tuple = 4, 5, 6
print(another_tuple)  # Output: (4, 5, 6)

Accessing Elements

Elements in a tuple can be accessed by their index . Remember that indexing in Python starts at 0 .

Code example:

my_tuple = (1, 2, 3)

print(my_tuple[0])  # Output: 1

Immutability

Once a tuple is created, you cannot change its elements.

my_tuple = (1, 2, 3)

my_tuple[0] = 10  # This will raise a TypeError

Iterating Through a Tuple

You can loop through the elements of a tuple using a for loop.

my_tuple = (1, 2, 3)

for item in my_tuple:
    print(item)

Tuple Length

To find out how many elements a tuple has, use the len() function.

my_tuple = (1, 2, 3)

print(len(my_tuple))  # Output: 3

Why Use Tuples?

Tuples are a fast data structure, making them suitable for creating a collection of constant values. They also guarantee that data remains unchanged, ensuring data integrity.