Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • compare list and set behavior
  • choose list or set for a given task
  • understand duplicate handling and ordering

List vs set at a glance

FeatureListSet
OrderOrderedUnordered
DuplicatesAllowedRemoved automatically
IndexingSupportedNot supported
Syntax[]{} or set()

List example

nums = [1, 2, 2, 3]
print(nums)  # [1, 2, 2, 3]

Set example

nums = {1, 2, 2, 3}
print(nums)  # {1, 2, 3}

Use cases

Use list when:
  • order matters
  • duplicates matter
  • indexing is needed
Use set when:
  • uniqueness matters
  • membership checking is primary
  • duplicate removal is required

Duplicate removal pattern

vals = [1, 2, 2, 3, 3, 4]
unique_vals = set(vals)
print(unique_vals)

Trap: empty set

a = {}
print(type(a))  # dict
Empty set must be:
a = set()

Exam hints and traps

  • set order should not be trusted in answers
  • set removes duplicates automatically
  • {} is empty dictionary, not empty set
  • list preserves insertion order

Quick practice

  1. Convert [1, 1, 2, 3, 3] to unique values.
  2. Which structure is better for roll numbers in attendance check?
  3. Why can you use nums[0] with list but not set?

Answer key

  1. set([1, 1, 2, 3, 3])
  2. Set, if only uniqueness and membership matter.
  3. Set is unordered and has no index positions.