Python Programming · High School (9–10) · 1 course, 13 worked problems, 26 practice questions
A tuple is like a list that cannot be changed once it is made, such as point = (3, 4). Tuples suit fixed data, such as coordinates or a date, and a function can return several values as a tuple. You can unpack a tuple into variables: x, y = point. A set is an unordered collection with no repeated items, written {1, 2, 3}. A set makes it easy to remove duplicates and to test whether an item belongs. Sets also support union, intersection and difference, as sets do in mathematics.
Choose an answer, then check it. Each one shows a full explanation.
Each pair in a list holds a letter and how many times to repeat it. The pairs are unpacked in the loop header, and the word that comes out becomes a tuple. pairs = [("a", 3), ("b", 0), ("c", 2)] word = "" for letter, times in pairs: word += letter * times chars = tuple(word) print(len(chars), chars.index("c"), chars.count("a")) What does the program print?
A program unpacks a tuple into two names, and then makes a longer tuple with +.
point = (3, 4)
x, y = point
point = point + (x * y,)
print(point, point.count(4), len(point))
What does the program print?
A function asks a tuple three questions and returns the three answers together. def info(t): return len(t), t.count(2), t.index(2) print(info((2, 4, 2, 6))) What does the program print?
A function tries to add one to the first item of a tuple. If that fails, it builds a new tuple instead. def bump(t): try: t[0] += 1 except TypeError: t = (t[0] + 1,) + t[1:] return t p = (1, 2) q = bump(p) print(p, q, p is q) What does the program print?
A tuple holds a list. The program changes the list and then tries to change the tuple. t = (1, [2, 3], 4) t[1].append(5) print(len(t), t[1]) t[2] += 1 What happens when the program runs?
A tuple is written with commas, and brackets alone do not make one. A student builds five values in different ways and asks Python for the type of each.
Which of the five tests give True? Choose every correct option.
One or more options are correct. Tick all the correct ones: a wrong option costs marks, and a part-right answer earns part of the marks.
Swapping by unpacking: after a, b = 3, 8 and then a, b = b, a, what is a?
Taking away a set: what does print(sorted({5, 6, 7, 8} - {6, 8})) show?
In exactly one of the two: what does print(sorted({1, 2, 3} ^ {3, 4})) show?
A tuple can be a dictionary key. What does print({(1, 2): "A", (3, 4): "B"}[(3, 4)]) show?
Each one has a hint, the key idea and a full worked solution.