What You Will Learn
Beginner
- What tuples are and when to use them
- Tuple vs list differences
- Tuple packing and unpacking
Terminalpython
# Creating tuples
point = (3, 4)
single = (42,) # Single element (note the comma!)
empty = ()
no_parens = 1, 2, 3 # Parentheses optional
# Accessing (same as lists)
print(point[0]) # 3
print(point[-1]) # 4
# Slicing
print(point[0:2]) # (3, 4)
# Length
print(len(point)) # 2Tuples vs Lists
| Aspect | List | Tuple |
|---|---|---|
| Mutability | Mutable | Immutable |
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Methods | Many (append, sort...) | Only count, index |
| Speed | Slower | Faster |
| Memory | More | Less |
| Use as dict key | No | Yes |
Tuple Unpacking
Terminalpython
# Unpacking
x, y = (3, 4)
print(x) # 3
print(y) # 4
# Swap variables
a, b = 10, 20
a, b = b, a # Swapped!
# Multiple return values
def min_max(numbers):
return min(numbers), max(numbers)
lowest, highest = min_max([3, 1, 4, 1, 5, 9])
print(lowest, highest) # 1 9When to use tuples
Use tuples for: fixed collections (coordinates, RGB colors), dictionary keys, multiple return values, data that should not change. Use lists for everything else.Practical Exercise
Create a tuple: point = (10, 20)
Access: print(point[0])
Try: point[0] = 5 - see the TypeError
Unpack: x, y = point
Create a tuple with one element: (42,)
Key Takeaways
- Tuples are immutable - cannot be changed after creation.
- Use (42,) for single-element tuple (comma required).
- Faster and smaller than lists.
- Can be used as dictionary keys (lists cannot).
- Unpacking: x, y = (3, 4). Great for multiple returns.
Comments
Comments
Post a Comment