Python Tuple Indexes
Just like lists, the items in a tuple are assigned an index, which allows you to access individual elements. Every item in a tuple has a unique index based on its position. Indexing starts at [0], meaning the first item has an index of [0], the second item has an index of [1], the third item has an index of [2], and so on. You can use these indexes to retrieve any specific item from the tuple.
country = ("Spain", "India", "US", "Germany")
# [0] [1] [2] [3]
Accessing tuple items:
1. Positive Indexing:
As we have seen that tuple items have an index, we can access items using these indexes.
Example:
country = ("Spain", "India", "US", "Germany")
print(country[0])
print(country[3])
print(country[2])
Output:
Spain
US
Germany
2. Negative Indexing:
Similar to positive indexing, negative indexing is also used to access items, but from the end of the tuple. The last item has index [-1], the second last item has index [-2], the third last item has index [-3], and so on.
Example:
country = ("Spain", "India", "US", "Germany")
print(country[0])
print(country[3])
print(country[2])
Output:
Germany
India
US
3. Range of Index (Tuple Slicing)
Instead of accessing a single item, you can access multiple items from a tuple by specifying a range of indexes. This is called tuple slicing.
Syntax:
Tuple[start : end : step]
-
startspecifies the index where the slice begins (inclusive). -
endspecifies the index where the slice ends (exclusive). -
The item at the
endindex is not included in the result. -
stepThe number of positions to move between items. It is optional, and the default value is 1.
Example:
country = ("Spain", "India", "US", "Germany", "Japan", "Canada") print(country[1:4])
Output:
('India', 'US', 'Germany')
In this example, the slice starts from index 1 (India) and ends before index 4 (Japan), so Japan is not included.
Slice from the Beginning
If you omit the start index, Python starts the slice from the first item.
Example:
country = ("Spain", "India", "US", "Germany", "Japan", "Canada") print(country[:3])
Output:
('Spain', 'India', 'US')
Slice to the End
If you omit the end index, Python returns all items from the specified start index to the end of the tuple.
Example:
country = ("Spain", "India", "US", "Germany", "Japan", "Canada") print(country[2:])
Output:
('US', 'Germany', 'Japan', 'Canada')
Using Negative Indexes
Negative indexes count from the end of the tuple.
Example:
country = ("Spain", "India", "US", "Germany", "Japan", "Canada")
print(country[-4:-1])
Output:
('US', 'Germany', 'Japan')
Here, refers to -4 and "US" refers to -1, which is excluded from the result.
"Canada"
Using Step Value
Example:
country = ("Spain", "India", "US", "Germany", "Japan", "Canada")
print(country[0:6:2])
Output:
('Spain', 'US', 'Japan')
The step value 2 returns every second item in the specified range.
Note: The item at the ending index is always excluded from the sliced result.