← Back to libraryQuestion 190 of 468
🐍PythonBeginner

Lists vs Tuples vs Sets

📌 Definition:

Lists are ordered, mutable sequences; tuples are ordered, immutable sequences; sets are unordered collections of unique elements. Each fits a different testing need.

📖 Detailed Explanation:

A list ([1, 2, 3]) supports append/remove and duplicates — use it for ordered, changing data like a sequence of test steps. A tuple ((200, 'OK')) is immutable and hashable — use it for fixed records (a status code + message) or as dict keys. A set ({1, 2, 3}) stores unique items with O(1) membership and supports union/intersection/difference — great for comparing expected vs actual id sets. Tuples are slightly faster and safer for constants; sets are unordered so you cannot index them.

🔑 Key Points:
  • List: ordered, mutable, allows duplicates (append/remove)
  • Tuple: ordered, immutable, hashable — good as dict keys/records
  • Set: unordered, unique, O(1) membership + set algebra
  • Pick tuple for fixed data, set for uniqueness, list for ordered mutable
🌍 Real-World Example:

Comparing API results to expected: missing = set(expected_ids) - set(actual_ids) instantly reveals which ids the API failed to return, using set difference — far cleaner than nested loops.

🎯 Scenario-Based Interview Question:

Why can a tuple be used as a dictionary key but a list cannot?