Python Tuples and Sets Practice Questions
Chapter 14 Recap and Practice
You now know all four Python collections. Here is the chapter in one table:
| You write | It means |
|---|---|
point = (3, 5) | a tuple: ordered, read by index, can't change |
point[0] = 10 | TypeError: a tuple can't change; build a new one instead |
("Sunny",) | a one-item tuple needs a comma; ("Sunny") is a string |
t.count(x), t.index(x) | how many times x appears, and where it first is |
name, age = person | unpacking: one name per item, the counts must match |
a, b = b, a | pack both values into a tuple, then unpack them: a swap |
for name, score in pairs: | unpack one pair every round |
for i, item in enumerate(items, 1): | the position and the item together |
colors = {"red", "blue"} | a set: each item once, no order, no index |
set() | an empty set; {} is an empty dictionary |
add(), remove(), discard() | put in, take out (error if missing), take out quietly |
sorted(set(my_list)) | the different items of a list, in order |
a | b, a & b, a - b | in either, in both, in the first only |
list(), tuple(), set() | pour the items into a new kind of collection |
{(1, 2), (3, 4)} | a set of tuples; a list can't go in a set |
And the four questions for picking a collection: look up by name? A dictionary. Unique? A set. Fixed? A tuple. Anything else? A list.
Practice questions
Use input() with no prompt text: the tests type every line for you. When a set is part of your answer, print it with sorted(), or print its len(), so the order is always the same.
Tuples
- 120.Python Program to Find the Day Name from a Number Using a TupleEasySolve
- 121.Python Program to Find the Day of the Year Using a TupleMediumSolve
Unpacking
- 122.Python Program to Swap Two Numbers Using Tuple UnpackingEasySolve
- 123.Python Program to Print a Marks Report from a List of TuplesMediumSolve
Sets
- 124.Python Program to Count Unique Words in a SentenceEasySolve
- 125.Python Program to Find the First Repeated WordMediumSolve
- 126.Python Program to Find Common Friends Using SetsMediumSolve
Which collection?
- 127.Python Program to Convert a List into a Set and a TupleEasySolve
- 128.Python Program to Count Different Points Using a Set of TuplesMediumSolve
- 129.Python Program to Make a Class Attendance ReportHardSolve
Lists, tuples, sets and dictionaries: pick the one that fits the job. Next, you'll learn to write your own functions.