![]() |
| Python Tuple tutorial explaining tuple creation, indexing, immutability, nested tuples, and conversion to list with examples. |
A Tuple is used to store multiple items in a single variable. It is a collection that is ordered, unchangeable, and allows duplicate values ✅.
📌 Creating a Tuple
sports = ("tennis", "cricket", "football")
print(len(sports))
len() function shows how many items are inside the tuple.
⚠ Single Item Tuple
To create a tuple with only one item, you must add a comma after the value.
tuple_1 = ("tennis",)
Without the comma, Python will treat it as a normal string.
📦 Different Data Types
Tuples can store different data types together.
my_tuple = ("tennis", 30, True)
🔢 Indexing in Tuple
Tuple items have index numbers starting from 0. You can also use negative indexing to access items from the end.
print(my_tuple[-1]) # Access last item
📚 Access Tuple Items (Range)
my_tuple = ("tennis", 30, "cricket", "football", True)
print(my_tuple[1:3]) # 30, cricket
print(my_tuple[:4]) # tennis, 30, cricket, football
print(my_tuple[2:]) # cricket, football, True
Range works the same way as lists. It starts from the first index and stops before the ending index.
✏ Update, Add, Remove Items
Tuples are unchangeable ❌. You cannot directly update, add, or remove items.
To modify a tuple:
- Convert tuple to list
- Change the list
- Convert back to tuple
my_tuple = ("tennis", 30, "cricket", "football", True)
y = list(my_tuple)
y[2] = "baseball"
my_tuple = tuple(y)
print(my_tuple)
📦 Nested Tuples
A Nested Tuple means a tuple inside another tuple.
nested_tuple = ((1,2,3), ("a","b","c"))
print(nested_tuple[0][1]) # 2
Here, [0] selects the first inner tuple and [1] selects the second value inside it.
🎯 Tuples are useful when you want to store data that should not be changed. They are commonly used in Data Science and structured data storage 🚀.
