JESKO GARAGE All topicsViva questions ▶ Open the practice garage

Python TUPLES (immutability) & SETS (unique elements): 11 practice problems

UNIT 2 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.

▶ Practise TUPLES (immutability) & SETS (unique elements) nowAll topics

Theory: TUPLES (immutability) & SETS (unique elements) in Python

THEORY — TUPLES
---------------
* Ordered, IMMUTABLE sequence:  point = (3, 4)   single = (5,)  ← the COMMA makes the tuple
  (5) is just the int 5.  Parentheses are optional: t = 1, 2, 3
* Same indexing/slicing as lists; only methods: count(), index().
* PACKING / UNPACKING:   x, y = point      a, b = b, a (swap)      first, *rest = (1, 2, 3)
      for name, marks in [("A", 90), ("B", 80)]:      # unpacking in loops
* Why tuples?  - data that must not change (coordinates, RGB colours, DB rows)
               - HASHABLE -> can be dict keys or set members:  {(0, 0): "origin"}
               - returning several values: return min_v, max_v
               - slightly faster & smaller than lists
* Immutable means you can't reassign items — but a tuple CONTAINING a list can have that list
  changed:  t = ([1], 2); t[0].append(9)  works!
* Tuples compare element by element: (2, "a") < (2, "b") -> True — handy for sorting keys.
* collections.namedtuple("Point", "x y")  gives named fields: p.x, p.y

THEORY — SETS
-------------
* Unordered collection of UNIQUE, hashable items:  {1, 2, 3}    set()  ← empty set ({} is a dict!)
* Membership test  x in s  is O(1) (hashing) — use sets for "have I seen this?"
* Methods: add(x), remove(x) (KeyError if missing), discard(x) (no error), pop(), clear(), update(iter)
* Operations              operator   method
      union                 a | b      a.union(b)
      intersection          a & b      a.intersection(b)
      difference            a - b      a.difference(b)          (in a, not in b)
      symmetric difference  a ^ b      a.symmetric_difference(b) (in exactly one)
      subset / superset     a <= b     a.issubset(b) / a.issuperset(b);  a.isdisjoint(b)
* Set comprehension: {x % 3 for x in range(10)} -> {0, 1, 2}
* frozenset — immutable set (can be a dict key or inside another set).
* Sets lose ORDER and DUPLICATES: sorted(set(x)) to get a sorted unique list.

11 TUPLES (immutability) & SETS (unique elements) practice problems

1. Min and Max in One Pass — return a tuple

Easy2 ways to solve
📤 OUTPUT: return a tuple (or None in the special case), e.g. (-2, 9). Use `return`, not print().
    min_max([4, -2, 9]) -> (-2, 9)     min_max([]) -> None
Ways: built-ins  ·  one loop tracking both (fewer passes)
Solve “Min and Max in One Pass — return a tuple” in your browser →

2. Rank Students — sort tuples with a key

Medium2 ways to solve
📤 OUTPUT: return a list, e.g. [('Asha', 90), ('Ali', 80), ('Ben', 80)]. Use `return`, not print().
records: list of (name, marks). Sort by marks DESC, then name ASC for ties.
    rank_students([("Ben", 80), ("Asha", 90), ("Ali", 80)]) -> [("Asha", 90), ("Ali", 80), ("Ben", 80)]
Hint: key=lambda r: (-r[1], r[0])
Solve “Rank Students — sort tuples with a key” in your browser →

3. Distance Between Two GPS-like Points — tuple unpacking

Easy2 ways to solve
📤 OUTPUT: return a float, e.g. 5.0. Use `return`, not print().
    distance((0, 0), (3, 4)) -> 5.0      (round to 2)
Solve “Distance Between Two GPS-like Points — tuple unpacking” in your browser →

4. Contains Duplicate (LeetCode 217)

Easy2 ways to solve
📤 OUTPUT: return a bool (True / False), e.g. True. Use `return`, not print().
    contains_duplicate([1, 2, 3, 1]) -> True      contains_duplicate([1, 2, 3]) -> False
Ways: len(set) vs len(list)  ·  loop with a `seen` set and early return
Solve “Contains Duplicate (LeetCode 217)” in your browser →

5. Missing Number (LeetCode 268)

Easy3 ways to solve
📤 OUTPUT: return an int, e.g. 2. Use `return`, not print().
Real world: Which roll number didn't submit? nums contains n distinct numbers from 0..n.
    missing_number([3, 0, 1]) -> 2
Ways: set difference  ·  maths: n(n+1)/2 - sum(nums)  ·  XOR trick
Solve “Missing Number (LeetCode 268)” in your browser →

6. Skills Every Candidate Has — intersection of many sets

Medium2 ways to solve
📤 OUTPUT: return a list, e.g. ['git', 'py']. Use `return`, not print().
Return a sorted list of items present in EVERY list. Empty input -> [].
    common_to_all([["py", "sql", "git"], ["git", "py"], ["py", "git", "c"]]) -> ["git", "py"]
Solve “Skills Every Candidate Has — intersection of many sets” in your browser →

7. Job Skill Gap — set difference

Easy2 ways to solve
📤 OUTPUT: return a tuple, e.g. (['git', 'sql'], ['excel']). Use `return`, not print().
Return (missing, extra): skills required but not had, skills had but not required (both sorted lists).
    skill_gap(["python", "excel"], ["python", "sql", "git"]) -> (["git", "sql"], ["excel"])
Solve “Job Skill Gap — set difference” in your browser →

8. Robot Vacuum Coverage — tuples inside a set

Medium2 ways to solve
📤 OUTPUT: return an int, e.g. 4. Use `return`, not print().
Real world: How many distinct floor cells did the robot clean?
Start at (0, 0) (counts as visited). Moves: "U" (y+1), "D" (y-1), "L" (x-1), "R" (x+1).
    robot_cells_visited("URDL") -> 4       robot_cells_visited("") -> 1
Solve “Robot Vacuum Coverage — tuples inside a set” in your browser →

9. Pair Names with Scores — zip -> list of tuples (stops at the shorter list)

Easy2 ways to solve
📤 OUTPUT: return a list, e.g. [('A', 90), ('B', 80)]. Use `return`, not print().
    zip_scores(["A", "B", "C"], [90, 80]) -> [("A", 90), ("B", 80)]
Solve “Pair Names with Scores — zip -> list of tuples (stops at the shorter list)” in your browser →

10. "People You May Know" — interview at a social-media company

Project1 way to solve
📤 OUTPUT: return a list, e.g. [('eli', 2), ('fay', 2)]. Use `return`, not print().
graph: {name: list of friends}. Candidates = friends of friends who are NOT the user and NOT already friends.
mutual = number of friends the candidate and the user share (set intersection).
Return the top k as [(name, mutual)], sorted by mutual DESC, then name ASC.
    suggest_friends(SOCIAL, "asha", 2) -> [("eli", 2), ("fay", 2)]
Solve “"People You May Know" — interview at a social-media company” in your browser →

11. Stage 10 — the Linter: find unused and undefined variables with SETS

Compiler1 way to solve
📤 OUTPUT: return a tuple, e.g. (['z'], ['w']). Use `return`, not print().
lines are like run_program's ("let NAME = ...", "print X").
defined = names after "let";  used = names on the right of "=" or after "print" (not numbers).
Return (unused, undefined): sorted lists. unused = defined but never used; undefined = used but never defined.
    analyze_symbols(["let x = 4", "let z = 1", "print x", "print w"]) -> (["z"], ["w"])
Solve “Stage 10 — the Linter: find unused and undefined variables with SETS” in your browser →

← DICTIONARIES (key-value storage) Functions & scope →