Python Tuples πΒΆ
Prerequisites: Python Lists
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 β