|
| 1 | +# ✅ Major difference between list and tuple: mutability |
| 2 | +# - Lists are mutable (can be modified) |
| 3 | +# - Tuples are immutable (cannot be modified) |
| 4 | + |
| 5 | +tea_types = ("Black tea", "Green", "Oolong") |
| 6 | +print("Original tuple:", tea_types) |
| 7 | +print("First tea type:", tea_types[0]) |
| 8 | + |
| 9 | +# ❌ This line will cause a TypeError because tuples are immutable |
| 10 | +# tea_types[0] = "change" # Uncommenting this will raise: TypeError |
| 11 | + |
| 12 | +# You can still find length |
| 13 | +print("Length of tuple:", len(tea_types)) |
| 14 | + |
| 15 | +# Tuples can be concatenated to make new tuples |
| 16 | +more_tea = ("Herbal", "Earl Grey") |
| 17 | +all_tea = more_tea + tea_types |
| 18 | +print("Concatenated tuple:", all_tea) |
| 19 | + |
| 20 | +# Tuple type check |
| 21 | +print("Type of tea_types:", type(tea_types)) # <class 'tuple'> |
| 22 | + |
| 23 | +# ✅ Additional add-ons: |
| 24 | +# ✅ Tuples can contain mixed data types |
| 25 | +mixed_tuple = ("Masala", 2, True) |
| 26 | +print("Mixed data tuple:", mixed_tuple) |
| 27 | + |
| 28 | +# ✅ You can nest tuples |
| 29 | +nested_tuple = (("green", "black"), ("hot", "cold")) |
| 30 | +print("Nested tuple:", nested_tuple) |
| 31 | + |
| 32 | +# ✅ You can iterate over a tuple just like a list |
| 33 | +for tea in tea_types: |
| 34 | + print("Tea variety:", tea) |
| 35 | + |
| 36 | +# ✅ You can convert tuple -> list to modify it |
| 37 | +tea_list = list(tea_types) |
| 38 | +tea_list[0] = "Changed tea" |
| 39 | +print("Modified list version of tuple:", tea_list) |
| 40 | + |
| 41 | +# ✅ Then convert back to tuple if needed |
| 42 | +tea_types = tuple(tea_list) |
| 43 | +print("Reconverted to tuple:", tea_types) |
0 commit comments