🐍 Tuples in Python
🔹 What is a Tuple in Python?A tuple in Python is a built-in data structure used to store multiple values in a single variable. Tuples are ordered, immutable (unchangeable), and allow duplicate values.
👉 Tuples are commonly used when data should not be modified.
✅ Why Use Tuples?
- Store fixed or constant data
- Faster and more memory-efficient than lists
- Provide data security due to immutability
- Can be used as dictionary keys
📌 Creating a Tuple
numbers = (1, 2, 3, 4)
names = ("Alice", "Bob", "Charlie")
mixed = (1, "Python", 3.5, True)
🔸 Single-Element Tuple
A comma is required to create a single-element tuple.
single = (10,)
📂 Types of Tuples in Python
1️⃣ Simple Tuple
Stores same type of elements.
marks = (80, 85, 90)
2️⃣ Mixed Tuple
Stores different data types.
data = (101, "Python", 9.8)
3️⃣ Nested Tuple
A tuple inside another tuple.
nested = ((1, 2), (3, 4))
4️⃣ Empty Tuple
empty = ()
📌 Accessing Tuple Elements
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # apple
print(fruits[-1]) # cherry
📌 Tuple Slicing
Extracts a portion of a tuple.
numbers = (10, 20, 30, 40, 50)
print(numbers[1:4]) # (20, 30, 40)
⚠️ Immutability of Tuples
Tuples cannot be modified after creation.
# This will cause an error
fruits[1] = "mango"
📌 Tuple Operations
🔹 Concatenation
t1 = (1, 2)
t2 = (3, 4)
result = t1 + t2
🔹 Repetition
repeat = ("Python",) * 3
🔹 Membership
"apple" in fruits
📚 Tuple Methods
| Method | Description |
|---|---|
| count() | Counts occurrences of an element |
| index() | Returns index of an element |
nums = (1, 2, 2, 3)
print(nums.count(2))
print(nums.index(3))
📌 Tuple Packing and Unpacking
🔹 Packing
data = 10, 20, 30
🔹 Unpacking
a, b, c = data
📌 Converting Tuple to List
Used when modification is required.
t = (1, 2, 3)
l = list(t)
l.append(4)
t = tuple(l)
✅ Advantages of Tuples
- Faster than lists
- Memory efficient
- Immutable (data security)
- Can be used as dictionary keys
❌ Disadvantages of Tuples
- Cannot modify elements
- Fewer built-in methods
📊 List vs Tuple (Quick Comparison)
| Feature | List | Tuple |
|---|---|---|
| Mutability | Mutable | Immutable |
| Syntax | [] | () |
| Speed | Slower | Faster |
| Methods | More | Fewer |
🌍 Real-World Use Cases
- Fixed data (coordinates, RGB values)
- Database records
- Function return values
- Configuration settings