A tuple is an ordered, immutable collection of items in Python. Unlike lists, tuples cannot be changed after creation. They can contain elements of different types.
my_tuple = (1, 2, 3)
mixed_tuple = (1, "hello", 3.14, True)
# 1. Accessing elements
colors = ("red", "green", "blue")
print(colors[1]) # Output: green
# 2. Nested tuples
nested = ((1, 2), (3, 4))
print(nested[0]) # Output: (1, 2)
print(nested[0][1]) # Output: 2
# 3. Tuple unpacking
point = (10, 20)
x, y = point
print(x) # Output: 10
print(y) # Output: 20
# 4. Single element tuple (note the comma)
single = (5,)
print(type(single)) # Output: <class 'tuple'>
# 5. Using tuples as dictionary keys
my_dict = { (1, 2): "point A", (3, 4): "point B" }
print(my_dict[(1, 2)]) # Output: point A