How do I index tuples in Python for beginners?

In Python, tuples are a collection of ordered items that are immutable, meaning they cannot be changed after they are created. Indexing a tuple allows you to access its elements using their positions. The indexing starts at 0, so the first element is at index 0, the second at index 1, and so forth. You can also use negative indexing to access elements from the end of the tuple.

Here’s a simple example of how to index a tuple:

# Creating a tuple my_tuple = (10, 20, 30, 40, 50) # Accessing elements using positive indexing first_element = my_tuple[0] # 10 second_element = my_tuple[1] # 20 # Accessing elements using negative indexing last_element = my_tuple[-1] # 50 second_last_element = my_tuple[-2] # 40 print("First element:", first_element) print("Second element:", second_element) print("Last element:", last_element) print("Second last element:", second_last_element)

Python tuples indexing tuples tuple examples Python for beginners