Junior
How does referencing elements in a regular tuple occur?
sobes.tech AI
Answer from AI
Tuple elements are accessible by their index, starting from 0, or through slices.
# Access by index
my_tuple = (10, 20, 30, 40, 50)
first_element = my_tuple[0] # 10
third_element = my_tuple[2] # 30
last_element = my_tuple[-1] # 50 - access from the end
# Access by slice
subset = my_tuple[1:4] # (20, 30, 40) - elements from index 1 to 3 (4 not included)
start_to_third = my_tuple[:3] # (10, 20, 30)
fourth_to_end = my_tuple[3:] # (40, 50)
all_elements = my_tuple[:] # (10, 20, 30, 40, 50) - a copy of the tuple
reversed_tuple = my_tuple[::-1] # (50, 40, 30, 20, 10)
You can also use tuple unpacking if the number of elements is known.
# Tuple unpacking
a, b, c, d, e = my_tuple
# Now a = 10, b = 20, etc.