Accessing elements in Python Tuples
To access an element in a Tuple at the given index use tuple[index]
.
Example
types = ( 'Motorbike', 'Car', 'Truck' ) element = types[0] # element will contain 'Motorbike'
In general you use tuple[index]
to access the element at position index
, where
index
starts at 0.
Negative indexes
You can access items in a Tuple by specifying a negative index, which means Python will count back
from the last element in the Tuple the number of places given by the (positive) value of
index
.
Example: Using a negative index
types = ( 'Motorbike', 'Car', 'Truck' ) element = types[-1] # element will contain 'Truck'
You can specify a range of indexes in order to return a Tuple that is a subset of the given Tuple. The start index specifies the index of first item to be included, and the end index is the index of the last item that will not be included.
Example: Extracting a subset from a Tuple
# indexes are: 0 1 2 3 types = ( 'Motorbike', 'Car', 'Truck', 'Boat' ) # We'll grab everyghing from 'Motorbike' (index 0) to 'Truck' (index 2). # Remember we need to add 1 to the index of the last item we want subtypes = types[0:3] # subtypes will contain ( 'Motorbike', 'Car', 'Truck')
Since we're starting from the first element in the Tuple we can simply leave out the first index in the range. The same goes if we wish the range to extend to the end of the list: just leave out the end index in this case.
# indexes are: 0 1 2 3 types = ( 'Motorbike', 'Car', 'Truck', 'Boat' ) subtypes = types[:3] # subtypes will contain ( 'Motorbike', 'Car', 'Truck') subtypes = types[2:] # subtypes will contain ('Truck', 'Boat')
And finally, you can use a range of negative indexes to specify the range. The first index indicates the element at which to start, and the last index indicates the element after the last element to include. Since the indexes are negative the indexes refer to items from the end of the Tuple
# indexes are: -4 -3 -2 -1 types = ( 'Motorbike', 'Car', 'Truck', 'Boat' ) subtypes = types[-3:-1] # subtypes will contain ('Car', 'Truck') subtypes = types[-3:] # subtypes will contain ('Car', 'Truck', 'Boat')
To iterate over a Tuple you can use len
to get
the number of elements in the tuple, and range
to create a range for a for
loop:
Example: Iterating over a Tuple
types = ( 'Motorbike', 'Car', 'Truck' ) length = len(types) for i in range(0, length - 1): print(types[i])