Level 1
0 / 100 XP

Python Tuples

In Python, a tuple is a data structure that stores an ordered collection of items. Unlike a list, a tuple is immutable, which means that the items in a tuple cannot be modified. In Python, tuples are represented by round brackets () and the items in a tuple are separated by commas.

Creating a Tuple

To create a tuple in Python, use round brackets () and separate the items in the tuple with commas. Here are some examples of creating tuples in Python:

Text
# Create an empty tuple my_tuple = () # Create a tuple of numbers numbers = (1, 2, 3, 4, 5) # Create a tuple of strings colors = ("red", "green", "blue") # Create a tuple of mixed data types mixed = (1, "two", 3.0, (4, 5))

As you can see, a tuple can store items of any data type, including other tuples.

Accessing and Modifying Tuple Items

In Python, you can access the items in a tuple using indexing. To access an item in a tuple, use the square bracket notation [] and specify the index of the item you want to access. In Python, the index of the first item in a tuple is 0, and the index of the last item in a tuple is -1. Here are some examples of accessing items in a tuple:

Python
# Access the first item in a tuple print(numbers[0]) # Output: 1 # Access the last item in a tuple print(numbers[-1]) # Output: 5 # Access a range of items in a tuple print(numbers[1:3]) # Output: (2, 3)

As you can see, you can access the items in a tuple using indexing, just like you would with a list. However, unlike a list, you cannot modify the items in an existing tuple, because tuples are immutable. If you try to modify a tuple, you will get a TypeError. For example:

Text
# Modify an item in a tuple (this will cause an error) numbers[0] = 10 # Output: TypeError: 'tuple' object does not support item assignment

In contr…