Practice: Tuple Methods

« Read the chapter

Q1. Count a value

BeginnerCoding

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

BeginnerCoding

Print the index of 'Ravi' in ('Asha', 'Ravi', 'Mina').

Goal: Use index().

Q3. Largest and smallest

BeginnerCoding

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

IntermediateCoding

Given t = (5, 2, 8, 1), print a tuple with the values in ascending order.

Goal: Convert sorted result.

Q5. Join and repeat

IntermediateCoding

Create a tuple that holds (1, 2) followed by (3, 4) and then print it repeated twice.

Goal: Use + and *.

Q6. Second match

AdvancedCoding

Print the index of the second 'a' in ('a', 'b', 'a', 'c').

Goal: Use start argument.

Q7. Replace an item

AdvancedCoding

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

BeginnerOutput

What does this print?

Code
t = (1, 2, 2, 3, 2)
print(t.count(2))

Goal: Predict count.

Q9. Index output

BeginnerOutput

What does this print?

Code
t = ('x', 'y', 'z', 'y')
print(t.index('y'))

Goal: Predict index.

Q10. Sum and len

BeginnerOutput

What does this print?

Code
t = (4, 6, 10)
print(sum(t) / len(t))

Goal: Predict average.

Q11. Type of sorted

IntermediateOutput

What does this print?

Code
t = (3, 1, 2)
print(type(sorted(t)).__name__)

Goal: Know sorted returns a list.

Q12. One-item tuple

IntermediateOutput

What does this print?

Code
a = (5)
b = (5,)
print(type(a).__name__, type(b).__name__)

Goal: Predict types.

Q13. Tuple comparison

IntermediateOutput

What does this print?

Code
print((1, 5) < (1, 7), (2, 0) < (1, 9))

Goal: Predict comparison.

Q14. Repeat and join

AdvancedOutput

What does this print?

Code
t = ('a',) * 3 + ('b',)
print(t, len(t))

Goal: Predict operators.

Q15. Mutable inside

AdvancedOutput

What does this print?

Code
t = ([1], 2)
t[0].append(9)
print(t)

Goal: List inside tuple.

Q16. Fix the append

BeginnerDebugging

This code fails. Fix it so it prints (1, 2, 3).

Code
t = (1, 2)
t.append(3)
print(t)

Goal: Build a new tuple.

Q17. Fix the missing index

IntermediateDebugging

This code crashes with ValueError. Fix it so it prints -1 when the value is missing.

Code
t = (4, 5, 6)
print(t.index(9))

Goal: Handle ValueError.

Q18. Fix the sort

IntermediateDebugging

This code fails because tuples have no sort(). Fix it to print (1, 2, 3).

Code
t = (3, 1, 2)
t.sort()
print(t)

Goal: Use sorted.

Q19. Why so few methods

BeginnerConceptual

Explain in one or two sentences why tuples have only count and index.

Goal: Explain immutability.

Q20. Index vs count

IntermediateConceptual

What is the difference in behaviour of index and count when the value is missing?

Goal: Compare methods.