Python Tuples
🐍 Python Tuples — Full Tutorial
A Tuple in Python is a collection of ordered, unchangeable (immutable) items.
Tuples are written using parentheses ():
✅ 1. Creating a Tuple
Empty Tuple:
Tuple with One Item (Important):
Use a comma, otherwise Python treats it as a normal variable:
🔹 2. Accessing Tuple Items (Indexing)
🔹 3. Tuple Slicing
🔹 4. Tuples are Immutable ❌ (Cannot Change)
🔹 5. But You Can Convert Tuple → List → Tuple ✔
🔹 6. Adding Items to a Tuple
Since tuples cannot be directly modified, we do:
🔹 7. Removing Items (Not Allowed)
But you can delete the entire tuple:
🔹 8. Looping Through a Tuple
🔹 9. Check if an Item Exists
🔹 10. Tuple Methods
| Method | Action |
|---|---|
count() |
Counts occurrences |
index() |
Returns index of value |
Example:
🔹 11. Tuple Packing and Unpacking
🔁 Unpack with * (Variable Length Items)
🔹 12. Nested Tuples
🔹 13. Tuple vs List
| Feature | Tuple | List |
|---|---|---|
| Syntax | () |
[] |
| Mutable | ❌ No | ✔ Yes |
| Faster | ✔ Yes | ❌ No |
| Use Case | Fixed data | Changing data |
🧠 When to Use Tuples?
✔ Store fixed data (like dates, coordinates, constant values)
✔ Faster performance
✔ Protect data from modification
Example:
