Improve your Python debugging skills by identifying and correcting common mistakes in tuple usage. Practice tuple syntax, immutability, and structure with real code examples.
Topic: tuples
Fix the tuple creation error in this code.
colors = ('red', 'green' 'blue')
print(colors)
Hint: 💡 Tuples require commas between elements.
Issue: Missing comma between 'green' and 'blue' causes string concatenation.
colors = ('red', 'green', 'blue')
print(colors)
Fix the incorrect tuple comparison.
t1 = (1, 2)
t2 = (1, 2, 3)
result = t1 > t2
print(result)
Hint: 💡 Longer tuples are considered greater if preceding elements are equal.
Issue: Incorrect comparison operator for the intended check.
t1 = (1, 2)
t2 = (1, 2, 3)
result = len(t1) > len(t2) # Or whatever comparison was intended
print(result)
Fix the tuple modification attempt.
coordinates = (10, 20, 30)
coordinates[1] = 25
print(coordinates)
Hint: 💡 Tuples are immutable - consider creating a new tuple.
Issue: Cannot modify tuple elements directly.
coordinates = (10, 20, 30)
new_coordinates = (coordinates[0], 25, coordinates[2])
print(new_coordinates)
Fix the incorrect single-element tuple creation.
single = (5)
print(type(single))
Hint: 💡 Single-element tuples require a trailing comma.
Issue: Without comma, it's just an integer in parentheses.
single = (5,)
print(type(single))
Fix the incorrect tuple method usage.
numbers = (1, 2, 3)
numbers.append(4)
print(numbers)
Hint: 💡 Tuples don't support append - consider alternatives.
Issue: Tuples are immutable and have no append method.
numbers = (1, 2, 3)
numbers = numbers + (4,)
print(numbers)
Fix the tuple unpacking error.
point = (1, 2, 3)
x, y = point
print(x, y)
Hint: 💡 Number of variables must match tuple length, or use extended unpacking.
Issue: Too many values to unpack (expected 2).
point = (1, 2, 3)
x, y, z = point
print(x, y)
# OR
x, y, _ = point
print(x, y)
Fix the slicing mistake to get the last two elements.
data = (10, 20, 30, 40)
last_two = data[2:3]
print(last_two)
Hint: 💡 Slice end index is exclusive - need to go beyond the last element.
Issue: Current slice only gets element at index 2.
data = (10, 20, 30, 40)
last_two = data[-2:]
print(last_two)