Lists, Tuples & Sets — Exercises
Work with sequence operations, comprehensions, uniqueness and immutability.
1. Lists
- Given
nums = [1,2,3,4,5]create a new list with squares using a list comprehension. - Remove duplicates from
[1,2,2,3,3,3]while preserving order.
2. Tuples
- Create a tuple representing a point
(x, y)and unpack intoxandy. - Convert a tuple to a list, modify it, then convert back to a tuple.
3. Sets
- Use sets to find common elements (intersection) of two lists.
- Given a sentence string, count unique words using sets (case-insensitive).
4. Mixed challenge
- Given list of tuples representing (name, score), produce a dict mapping name → highest score (use loops or comprehensions).
- Given a large list of numbers, show how sets can speed up membership tests compared to lists (explain with simple timing code example).
Show answers — Collections worksheet
1. Lists
# 1. squares using comprehension
nums = [1,2,3,4,5]
squares = [x*x for x in nums]
# 2. remove duplicates while preserving order
arr = [1,2,2,3,3,3]
seen = set()
result = []
for x in arr:
if x not in seen:
seen.add(x)
result.append(x)
print(result) # [1,2,3]
2. Tuples
# 3. unpack point
point = (3,4)
x, y = point
# 4. convert tuple to list, modify, convert back
t = (1,2,3)
lst = list(t)
lst[0] = 99
t2 = tuple(lst)
3. Sets
# 5. intersection of lists
a = [1,2,3]
b = [2,3,4]
common = list(set(a) & set(b))
# 6. unique words (case-insensitive)
s = "Hello hello world"
words = {w.lower() for w in s.split()}
print(words)
4. Mixed challenge
# 7. map name -> highest score
data = [("A", 10), ("B", 20), ("A", 15)]
best = {}
for name, score in data:
best[name] = max(best.get(name, 0), score)
print(best)
# 8. timing membership difference (simple demonstration)
import time
large = list(range(1000000))
t0 = time.time()
999999 in large
t1 = time.time()
s = set(large)
t2 = time.time()
999999 in s
t3 = time.time()
print("list check:", t1-t0, "set check:", t3-t2)