Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 08

Python Sets

3 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

A set is an unordered collection of unique items.

You will learn creation, mathematical set operations, the set methods, and how a set differs from a dictionary.

Sets give very fast membership tests and automatic duplicate removal.

Unique visitors, removing duplicates, finding common friends, tag filtering.

1

Python Sets

A set is an unordered, mutable collection of UNIQUE, hashable items written inside curly braces, e.g. {1, 2, 3}. Duplicates are removed automatically and items have no index.

In short: A set is a bag of distinct things. Putting the same thing in twice keeps just one.

Set = unique items only

Think about it

Many problems become simple when you can ask "is it present?" or "what is common?" in one operation. Two students list their hobbies; the intersection shows common hobbies.

Create with {1, 2, 3} or `set(iterable)`.

An EMPTY set must be set() because {} creates an empty dictionary.

Items must be hashable (numbers, strings, tuples), so a list or another set cannot be inside a set.

Because there is no order, indexing and slicing are not allowed and the printed order may vary.

Membership x in s is O(1) on average, much faster than in a list.

Mathematical operators: | union, & intersection, - difference, ^ symmetric difference, <= subset, >= superset.

A frozenset is an immutable set that can itself be a set item or dict key.

Set comprehension: {x % 3 for x in range(10)}.

Note that 1, 1.0 and True count as the same element.

Key points

  • Unique: No duplicates are stored.
  • Unordered: No positions, so no indexing.
  • Hashable: Items must have a fixed hash, so they must be immutable.
  • frozenset: Immutable version of a set.

Example

Code
Set creation and set operators:
s = {3, 1, 2, 3, 1}
print(s)                       # {1, 2, 3}   (duplicates removed)

empty_set = set()              # NOT {}
empty_dict = {}
print(type(empty_set), type(empty_dict))   # set dict

print(set([1, 2, 2, 3]))       # {1, 2, 3}
print(set("hello"))            # {'h', 'e', 'l', 'o'}  (order may vary)
print(list(set([3, 3, 1, 2]))) # remove duplicates from a list

print(2 in s, 9 in s)          # True False

a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b)                   # {1, 2, 3, 4, 5}
print(a & b)                   # {3, 4}
print(a - b)                   # {1, 2}
print(a ^ b)                   # {1, 2, 5}
print({1, 2} <= a)             # True (subset)

# s[0]                         # TypeError: sets are not indexable
# {[1, 2]}                     # TypeError: unhashable type: 'list'

evens_mod = {x % 3 for x in range(10)}
print(evens_mod)               # {0, 1, 2}

fs = frozenset([1, 2])
print({fs: "ok"})              # frozenset can be a dict key
2

Python Set Methods

Set methods add, remove, combine and compare sets. Key ones are add, update, remove, discard, pop, clear, union, intersection, difference, symmetric_difference, issubset, issuperset, isdisjoint and copy.

In short: They are the named versions of the set operators plus tools to add and delete members.

Set methods change membership

Think about it

Output prediction and remove vs discard are classic exam points. Removing blocked users from a list of members using difference().

Adding: add(x) one item, `update(iterable)` many items.

Removing: remove(x) raises KeyError if missing, discard(x) does nothing if missing, pop() removes an ARBITRARY item, clear() empties the set.

Combining (return a NEW set): union, intersection, `difference, symmetric_difference`.

The in-place forms update, intersection_update, `difference_update and symmetric_difference_update` change the original set.

Comparison

issubset, issuperset, isdisjoint return booleans.

Methods accept any iterable (a list works), while operators need both sides to be sets.

copy() makes a shallow copy.

A frequent mistake: `s.

add([1, 2])` fails because a list is unhashable; use a tuple.

Key points

  • remove vs discard: remove raises KeyError if absent; discard stays silent.
  • Symmetric difference: Items in either set but not in both.
  • isdisjoint: True when two sets share no items.

Example

Code
Set methods:
s = {1, 2}
s.add(3)
s.update([3, 4, 5])
print(s)                         # {1, 2, 3, 4, 5}

s.remove(5)
s.discard(99)                    # no error
# s.remove(99)                   # KeyError
print(s.pop() in {1, 2, 3, 4})   # True (arbitrary item removed)

a = {1, 2, 3}
b = {3, 4}
print(a.union(b))                # {1, 2, 3, 4}
print(a.intersection(b))         # {3}
print(a.difference(b))           # {1, 2}
print(a.symmetric_difference(b)) # {1, 2, 4}
print(a.union([7, 8]))           # methods accept any iterable

print({1}.issubset(a), a.issuperset({1, 2}), a.isdisjoint({9}))  # True True True

a.intersection_update(b)         # in place
print(a)                         # {3}

t = {1, 2}.copy()
t.clear()
print(t)                         # set()

# s.add([1, 2])                  # TypeError: use a tuple instead
s.add((1, 2))

add / update

Insert one item or many items.

remove / discard / pop / clear

Delete one item (strict or safe), an arbitrary item, or everything.

union / intersection / difference

Return new sets using set algebra.

issubset / issuperset / isdisjoint

Return True or False for relationships between sets.

3

Difference between Set and Dictionary in Python

A set stores unique items only and is written {1, 2}; a dictionary stores key-value pairs and is written {"a": 1}. Both use curly braces and both need hashable keys/items, but a set has no values.

In short: A set is a list of unique names. A dictionary is a phone book: a name (key) with a number (value).

Compare two ideas side by side

Think about it

The shared braces confuse beginners, so this comparison is a common viva question. Set: unique roll numbers present today. Dictionary: roll number to student name.

Elements: set holds single items, dict holds key:value pairs.

Empty: set() versus {}.

Order: dictionaries keep insertion order (Python 3.7+), sets do not guarantee any order.

Access: dict d[key] returns the value; sets cannot be accessed by index or key, only tested with in.

Duplicates: set drops duplicate items; dict keeps one value per key (a repeated key overwrites).

Operators: sets support | & - ^; dicts support | merge (3.9+) but no intersection.

Both offer O(1) average lookup.

Choose a set to ask "is it there?

" and a dict to ask "what is associated with it?

".

Key points

  • Key: Unique hashable label used to look up a value in a dictionary.
  • Value: Data stored against a key; sets have none.

Example

Code
Set vs dictionary:
s = {1, 2, 3}                    # set
d = {1: "one", 2: "two"}         # dictionary
print(type(s), type(d))          # set dict

print(2 in s, 2 in d)            # True True  (dict checks keys)
print(d[2])                      # two
# print(s[2])                    # TypeError: set is not subscriptable

d2 = {"a": 1, "a": 2}
print(d2)                        # {'a': 2}  (later value wins)
print({1, 1, 2})                 # {1, 2}

print({1, 2} | {2, 3})           # {1, 2, 3}
print({"a": 1} | {"b": 2})       # {'a': 1, 'b': 2}   (Python 3.9+)

print(type({}), type(set()))     # dict set

Solved examples

Example 01 · Basic

Remove duplicates from [4, 2, 4, 1, 2] and show the sorted unique values.

Given Data:
    Required To Find:

    Sorted unique list

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: set(list) removes duplicates
    Step 2: sorted() returns a sorted list
    Final Answer: sorted(set([4, 2, 4, 1, 2])) → [1, 2, 4]

    Approach note: Converting to a set loses the original order.

    Example 02 · Intermediate

    Two clubs: A = {"ann", "raj", "li"} and B = {"raj", "sam"}. Find members in both and members in only A.

    Given Data:
      Required To Find:

      Two sets

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Both: A & B
      Step 2: Only A: A - B
      Final Answer: A & B = {"raj"}; A - B = {"ann", "li"}

      Approach note: Difference is not symmetric: A - B differs from B - A.

      Example 03 · Basic

      What is type({})?

      Given Data:
        Required To Find:

        Type name

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Empty braces always make a dictionary
        Step 2: Use set() for an empty set
        Final Answer: <class 'dict'>

        Approach note: Memorise: {} is a dict.

        Example 04 · Intermediate

        Given nums = [1, 2, 2, 3, 3, 3, 4], print the count of unique values using a set.

        Given Data:
          Required To Find:

          Unique count

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Convert the list to a set to drop duplicates
          Step 2: set becomes {1, 2, 3, 4}
          Step 3: len of that set is 4
          Final Answer: print(len(set([1, 2, 2, 3, 3, 3, 4]))) # 4

          Approach note: len(set(seq)) is the classic unique-count one-liner.

          Real-world applications

          Python

          Using Python Sets in real projects

          Unique visitors, removing duplicates, finding common friends, tag filtering.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: {} creates an empty set.

          Why this is wrong: It creates an empty dictionary.

          ✅ Verified Truth: Use set().

          ⚠️ Exam Tip: A guaranteed MCQ.

          ❌ Myth: Sets keep insertion order.

          Why this is wrong: Sets are unordered.

          ✅ Verified Truth: Dictionaries keep insertion order, sets do not.

          ⚠️ Exam Tip: Never rely on set order.

          ❌ Myth: A set can contain lists.

          Why this is wrong: Lists are mutable and unhashable.

          ✅ Verified Truth: Store tuples or frozensets instead.

          ⚠️ Exam Tip: Remember the hashable rule.

          Revision notes

          A set is an unordered collection of unique items. You will learn creation, mathematical set operations, the set methods, and how a set differs from a dictionary.

          High-Yield Quick Revision Points

          1. Set = unique, unordered, mutable, hashable items
          2. Empty set is set(), {} is dict
          3. | & - ^ operators and their methods
          4. remove raises KeyError; discard does not
          5. No indexing on sets
          6. Set holds items; dict holds key:value pairs

          Practice questions

          Question 1 · MCQ (Interview / semester)

          len({1, 2, 2, 3, 3, 3})?

          Question 2 · MCQ (Interview / semester)

          Which creates an empty set?

          Question 3 · MCQ (Interview / semester)

          Which raises KeyError for a missing item?

          Question 4 · MCQ (Interview / semester)

          {1, 2, 3} & {2, 3, 4} equals

          Question 5 · MCQ (Interview / semester)

          Which operator gives symmetric difference?

          Question 6 · MCQ (Interview / semester)

          Which of these can be stored in a set?