Tuple Indexes
In Python, tuple indexing works similarly to list indexing. Tuples are zero-indexed, meaning that the first element has an index of 0, the second element has an index of 1, and so on. You can access elements in a tuple using square brackets []
with the index of the desired element. Here are some examples:
- Accessing Elements:
- Elements in a tuple are accessed using zero-based indexing.
numbers = (10, 20, 30, 40, 50) first_element = numbers[0] # 10 third_element = numbers[2] # 30
- Elements in a tuple are accessed using zero-based indexing.
- Negative Indexing:
- Negative indices count from the end of the tuple, with -1 representing the last element.
numbers = (10, 20, 30, 40, 50) last_element = numbers[-1] # 50 second_last_element = numbers[-2] # 40
- Negative indices count from the end of the tuple, with -1 representing the last element.
- Slicing:
- You can use slicing to get a subset (a range of elements) from a tuple.
numbers = (10, 20, 30, 40, 50) sub_tuple = numbers[1:4] # (20, 30, 40)
- You can use slicing to get a subset (a range of elements) from a tuple.
- Immutable Nature:
- Tuples are immutable, so you cannot change their elements once they are created.
numbers = (10, 20, 30) # Attempting to modify a tuple will result in an error # numbers[0] = 5 # Raises TypeError
- Tuples are immutable, so you cannot change their elements once they are created.
- Tuple Packing and Unpacking:
- You can pack multiple values into a tuple, and then unpack them into variables.
coordinates = (3, 4) x, y = coordinates # Now, x is 3 and y is 4
- You can pack multiple values into a tuple, and then unpack them into variables.
Tuple indexing provides a way to access individual elements or slices of elements within a tuple. Keep in mind that, unlike lists, tuples are immutable, so their elements cannot be modified after creation. If you need a collection with elements that can be changed, you may want to use a list instead of a tuple.