Tuples in Python

A tuple is a collection of ordered, immutable items in Python. Once a tuple is created, its values cannot be changed, making it useful for data that shouldn’t be altered.

Creating a Tuple

You can create a tuple using parentheses () and separating the items with commas. Here’s an example:

my_tuple = (1, 2, 3)

Accessing Tuple Items

Like lists, you can access tuple items by their index, starting from 0:

print(my_tuple[0])  # Outputs: 1
print(my_tuple[2])  # Outputs: 3

Immutability of Tuples

Unlike lists, tuples cannot be changed after they are created. This means you cannot add, remove, or modify items in a tuple:

# This will raise an error
my_tuple[1] = 4

Why Use Tuples?

Tuples are often used when you want to store data that should not be changed throughout the life of the program. They also have performance advantages in some cases due to their immutability.

Tuple Methods

Even though tuples are immutable, there are a few methods you can use with them:

my_tuple = (1, 2, 3, 2)
print(my_tuple.count(2))  # Outputs: 2
print(my_tuple.index(3))  # Outputs: 2

Exercise

Create a tuple with the names of your favorite cities. Use a method to find the index of one of the cities in the tuple, and try printing it.