Accessing Items
-
This lesson teaches how to access tuple elements using index numbers.
Since tuples are ordered, each item has an index number starting from 0.
Access Using Index
Each item in a tuple has a position (index). We use the index number to get the value.
colors = ("red", "green", "blue", "yellow")
print(colors[0]) # First item
print(colors[2]) # Third item
Explanation
Index starts from 0
colors[0] → red
colors[2] → blue
Negative Indexing
Negative indexing starts from the end of the tuple.
numbers = (10, 20, 30, 40, 50)
print(numbers[-1])
print(numbers[-2])
Explanation
-1 → last element (50)
-2 → second last (40)
Range of Indexes (Slicing)
We can access multiple items using slicing.
days = ("Mon", "Tue", "Wed", "Thu", "Fri")
print(days[1:4])
Explanation
Starts from index 1
Ends before index 4
Output → ('Tue', 'Wed', 'Thu')
Check if Item Exists
We can check whether an item is present using in keyword.
fruits = ("apple", "banana", "mango")
if "banana" in fruits:
print("Yes, banana exists")
Loop Through Tuple
We can access all items using loops.
cars = ("BMW", "Audi", "Tesla")
for car in cars:
print(car)