Practice: Tuple Methods
Q1. Count a value
Write code that counts how many times 3 appears in (3, 1, 3, 2, 3) and prints it.
Goal: Use count().
Q2. Position of a name
Print the index of 'Ravi' in ('Asha', 'Ravi', 'Mina').
Goal: Use index().
Q3. Largest and smallest
Print the smallest and largest values of (14, 3, 27, 9) on one line separated by a space.
Goal: Use min and max.
Q4. Sorted tuple
Given t = (5, 2, 8, 1), print a tuple with the values in ascending order.
Goal: Convert sorted result.
Q5. Join and repeat
Create a tuple that holds (1, 2) followed by (3, 4) and then print it repeated twice.
Goal: Use + and *.
Q6. Second match
Print the index of the second 'a' in ('a', 'b', 'a', 'c').
Goal: Use start argument.
Q7. Replace an item
Replace the middle value of (1, 2, 3) with 20 by building a new tuple and print it.
Goal: Build a new tuple.
Q8. Count output
What does this print?
t = (1, 2, 2, 3, 2)
print(t.count(2))Goal: Predict count.
Q9. Index output
What does this print?
t = ('x', 'y', 'z', 'y')
print(t.index('y'))Goal: Predict index.
Q10. Sum and len
What does this print?
t = (4, 6, 10)
print(sum(t) / len(t))Goal: Predict average.
Q11. Type of sorted
What does this print?
t = (3, 1, 2)
print(type(sorted(t)).__name__)Goal: Know sorted returns a list.
Q12. One-item tuple
What does this print?
a = (5)
b = (5,)
print(type(a).__name__, type(b).__name__)Goal: Predict types.
Q13. Tuple comparison
What does this print?
print((1, 5) < (1, 7), (2, 0) < (1, 9))Goal: Predict comparison.
Q14. Repeat and join
What does this print?
t = ('a',) * 3 + ('b',)
print(t, len(t))Goal: Predict operators.
Q15. Mutable inside
What does this print?
t = ([1], 2)
t[0].append(9)
print(t)Goal: List inside tuple.
Q16. Fix the append
This code fails. Fix it so it prints (1, 2, 3).
t = (1, 2)
t.append(3)
print(t)Goal: Build a new tuple.
Q17. Fix the missing index
This code crashes with ValueError. Fix it so it prints -1 when the value is missing.
t = (4, 5, 6)
print(t.index(9))Goal: Handle ValueError.
Q18. Fix the sort
This code fails because tuples have no sort(). Fix it to print (1, 2, 3).
t = (3, 1, 2)
t.sort()
print(t)Goal: Use sorted.
Q19. Why so few methods
Explain in one or two sentences why tuples have only count and index.
Goal: Explain immutability.
Q20. Index vs count
What is the difference in behaviour of index and count when the value is missing?
Goal: Compare methods.