c2cedge
C, Java & Python · D — Python Essentials

Python: Lists, Tuples, Dicts & Sets

Python's built-in collections are the workhorses of every program. Knowing what each is for, and their costs, answers most practical Python questions.

Test weight: Very high (Py)Skill: Pick the structureDifficulty: Easy–Medium

Python ships four core collections: list (ordered, mutable, allows duplicates), tuple (ordered, immutable), dict (key–value mapping), and set (unordered collection of unique items). Choosing the right one — and knowing slicing and lookup costs — covers most everyday Python.

The four collections

list [1,2,3]: ordered, mutable, indexable. tuple (1,2,3): like a list but immutable, so it's hashable and can be a dict key. dict {'a':1}: O(1) average key lookups, insertion-ordered (3.7+). set {1,2,3}: unique items, O(1) membership tests.

Core operations
nums = [1, 2, 3, 4]
print(nums[1:3])      # [2, 3]   slicing returns a NEW list
nums.append(5)        # [1,2,3,4,5]

ages = {"Asha": 30}
print(ages.get("Bob", 0))  # 0  (safe default; ages["Bob"] would KeyError)

unique = set([1, 1, 2, 3])  # {1, 2, 3}
print(2 in unique)          # True  (fast membership)
⚡ The edge
  • Slicing a list returns a new list (a shallow copy of that range), so nums[:] is a quick way to copy. Use a tuple when the sequence shouldn't change — it's also hashable, so it can be a dict key or set member.
  • Use dict.get(key, default) to avoid KeyError when a key might be missing. Choose a set for uniqueness and fast in membership tests — it's far faster than scanning a list.
Worked example
When would you use a tuple instead of a list?
  1. When the sequence shouldn't change — immutability signals intent and prevents accidental modification.
  2. When you need a hashable sequence — e.g. as a dictionary key or an element of a set (lists can't be).
  3. Tuples are also slightly lighter. Use a list when you need to add, remove or reorder elements.
Worked example
How do you safely look up a key that might not exist in a dict?
  1. Indexing a missing key (d[k]) raises KeyError.
  2. Use d.get(k) which returns None (or a default you supply) instead of raising.
  3. Or check membership first with 'if k in d', or use collections.defaultdict for auto-defaults.
⚠ Watch out
  • Shallow vs deep copy: nums[:] copies the list but not nested objects inside it.
  • d[missing] raises KeyError; prefer .get() or in.
  • Lists can't be dict keys or set members (unhashable); use a tuple.
Practice this — take a timed mock →
1,300+ questions, scored, with a weak-area report.
Know who's ready. Not who finished.
HomeLibraryPrivacyTerms