Tuples in Python are ordered, immutable collections. Once a tuple is created, its items cannot be changed, but you can easily access any element using indexing, negative indexing, slicing, and membership checks.
0, just like lists and strings.-1) access elements from the end of the tuple.in keyword checks if a value exists inside a tuple.Given a tuple:
my_tuple = (v1, v2, v3, ...)
my_tuple[index]my_tuple[-1] (last item), my_tuple[-2] (second last), etc.my_tuple[start:end] (from start up to, but not including, end)my_tuple[:end] → from the beginning to end - 1my_tuple[start:] → from start to the endvalue in my_tuple → True or FalseYou can access tuple items by referring to their index number. Indexing starts at 0.
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # apple
print(fruits[2]) # cherry
Negative indexes allow you to access items from the end of the tuple.
fruits = ("apple", "banana", "cherry")
print(fruits[-1]) # cherry
print(fruits[-2]) # banana
You can specify a range of indexes to return a new tuple containing only selected items.
fruits = ("apple", "banana", "cherry", "mango", "orange")
print(fruits[1:4]) # ('banana', 'cherry', 'mango')
print(fruits[:3]) # ('apple', 'banana', 'cherry')
print(fruits[2:]) # ('cherry', 'mango', 'orange')
Use the in keyword to check if an item exists in a tuple.
fruits = ("apple", "banana", "cherry")
# Check whether 'banana' exists in the tuple
if "banana" in fruits:
print("Yes, 'banana' is in the tuple!")
apple
cherry
fruits[0] is the first item ("apple") and fruits[2] is the third item ("cherry").
cherry
banana
fruits[-1] goes from the end (last item), and fruits[-2] is the second-last item.
('banana', 'cherry', 'mango')
('apple', 'banana', 'cherry')
('cherry', 'mango', 'orange')
Each slice returns a new tuple with only the selected elements, based on the given index range.
Yes, 'banana' is in the tuple!
The condition "banana" in fruits evaluates to True, so the message is printed.
0.fruits[10]) raises an IndexError.in operator instead of looping when you only need to check if a value exists.1–10 using the in operator.my_tuple[::2].