Python Tuples ๐¶
Mentor's Note: If a List is an open shopping bag, a Tuple is a Locked Box. Once you put things inside and close it, you cannot change them! ๐ก
๐ The Scenario: The GPS Coordinates ๐¶
Imagine you are a navigator tracking a treasure chest.
- The Logic: The location is fixed at Latitude 21.17 and Longitude 72.83. If someone accidentally changed these numbers, you would never find the treasure! ๐ฆ
- The Result: You put these numbers into a Tuple. Because it is "Locked" (Immutable), no one can accidentally change the location. โ
๐ Concept Explanation¶
1. What is a Tuple?¶
A tuple is a collection which is ordered and unchangeable (Immutable).
2. Creating a Tuple¶
Tuples are written with round brackets ().
3. Why use a Tuple?¶
- Safety: Protect data that should never change.
- Speed: Tuples are slightly faster than lists.
- Keys: Tuples can be used as keys in a dictionary (Lists cannot).
๐จ Visual Logic: List vs. Tuple¶
graph LR
subgraph List: ["Changeable ๐"]
A[Value] -- swap --> B[New Value]
end
subgraph Tuple: ["Locked ๐"]
C[Value] -- X --> D[No Changes!]
end
๐ป Implementation: Tuple Lab¶
# ๐ Scenario: A Locked Record
# ๐ Action: Creating and unpacking a tuple
# 1. Creation
user_record = ("ID101", "Vishnu", "Admin")
# 2. Access
print(user_record[1]) # Output: Vishnu
# 3. โ ๏ธ Attempting to change (WILL ERROR)
# user_record[1] = "Ankit" # โ TypeError
# 4. Unpacking (Magic!) โจ
id, name, role = user_record
print(f"Role of {name} is {role}.")
# ๐๏ธ Outcome: "Role of Vishnu is Admin."
๐ Sample Dry Run (Unpacking)¶
Tuple: T = ("Red", "Blue")
| Step | Instruction | color1 |
color2 |
Description |
|---|---|---|---|---|
| 1 | color1, color2 = T |
"Red" |
"Blue" |
Values extracted into variables ๐ฅ |
๐ Technical Analysis¶
- Memory: Tuples use less memory than lists because they don't need to plan for future growth.
- Iteration: Since they are immutable, Python iterates over tuples faster.
๐ฏ Practice Lab ๐งช¶
Task: The Fixed Menu
Task: Create a tuple named menu with 3 items. Try to change the second item. Notice the error. Then, convert the tuple to a list, change the item, and convert it back!
Hint: list(menu) and tuple(my_list). ๐ก
โ Back: Lists | Next: Sets โ