How to access items of a tuple in Python
Published on Aug. 22, 2023, 12:16 p.m.
To access items of a tuple in Python, you can use indexing to refer to individual elements of the tuple. Indexing starts at 0 for the first element, 1 for the second element, and so on.
Here’s an example:
my_tuple = ('apple', 'banana', 'cherry')
# Access the first element of the tuple
print(my_tuple[0]) # Output: 'apple'
# Access the second element of the tuple
print(my_tuple[1]) # Output: 'banana'
# Access the third element of the tuple
print(my_tuple[2]) # Output: 'cherry'
In this example, we first define a tuple my_tuple
containing three string elements. We then use indexing to access the first, second, and third element of the tuple, and print each one to the console.
Note that you cannot modify the individual elements of a tuple since tuples are immutable.