Python Set Methods

In the last lesson you learned Difference. There you compared two sets to find what one has that the other does not. That was about reading sets. Now we look at the methods that actually change a set. We also cover a couple of handy ones that ask questions about it.

πŸ€” Why Set Methods?

Say you are keeping a set of usernames that liked a post. People click like. People unlike. People click again. You need to add a name, take one out, empty the whole thing, or merge in a fresh batch of names. Doing all that by hand is slow and easy to get wrong.

Set methods are the ready-made tools for exactly this. Each one does a single clear job. So you just call the right method and the set updates for you.

βž• Adding Items: add() and update()

The add() method puts one item into the set. If the item is already there, nothing changes. A set never keeps duplicates.

This adds a couple of names to a set of people who liked a post.

likes = {"alex", "riya"}
likes.add("arjun")
likes.add("alex") # already there, so no change
print(likes)

Output

{'alex', 'riya', 'arjun'}

The order you see may differ on your machine. A set does not keep things in order. That is normal.

When you want to add many items at once, use update(). It takes another set, or any list of items, and adds all of them at once.

This merges a new batch of names into the existing set.

likes = {"alex", "riya"}
likes.update(["arjun", "maya", "alex"])
print(likes)

Output

{'alex', 'riya', 'arjun', 'maya'}

So add() is for one item and update() is for many. The repeated β€œalex” was dropped. A set keeps each value only once.

βž– Removing Items: remove(), discard(), and pop()

There are three ways to take something out, and the difference matters.

The remove() method deletes the item you name. But if that item is not in the set, it raises an error and your program stops.

This removes one name that we know is in the set.

likes = {"alex", "riya", "arjun"}
likes.remove("riya")
print(likes)

Output

{'alex', 'arjun'}

Now watch what happens when the name is not there.

likes = {"alex", "arjun"}
likes.remove("maya")

Output

Traceback (most recent call last):
File "likes.py", line 2, in <module>
likes.remove("maya")
KeyError: 'maya'

The discard() method does the same job, but it stays calm when the item is missing. No error, no crash. It just does nothing.

This tries to remove a name that is not in the set, and the program keeps running fine.

likes = {"alex", "arjun"}
likes.discard("maya") # not there, but no error
likes.discard("alex") # this one is there, so it goes
print(likes)

Output

{'arjun'}

So if you are not sure the item is in the set, use discard(). It saves you from a crash.

The pop() method is different. It removes and gives back one item, but you do not get to choose which one. A set has no order, so pop just hands you whatever it grabs.

This pulls one name out of the set and prints which one came out.

names = {"alex", "riya", "arjun"}
picked = names.pop()
print("removed:", picked)
print("left:", names)

Output

removed: alex
left: {'riya', 'arjun'}

The name you see may be different when you run it, since the choice is not yours. If the set is empty, pop() raises an error. So only pop when you know there is something inside.

🧹 Emptying and Copying: clear() and copy()

The clear() method empties the whole set in one go. You are left with an empty set, not None.

This wipes every name out of the set.

likes = {"alex", "riya", "arjun"}
likes.clear()
print(likes)

Output

set()

Notice it prints set(), not {}. Empty curly braces mean an empty dictionary in Python. So an empty set has its own way of showing itself.

The copy() method makes a separate second set with the same items. Why bother? Because if you just write b = a, both names point at the same set. Then changing one changes the other. A copy is its own thing.

This shows the trap first, then the fix.

a = {"alex", "riya"}
# ❌ Avoid: this is not a copy, both names share one set
b = a
b.add("maya")
print(a) # a changed too!
# βœ… Good: copy() gives a real separate set
c = a.copy()
c.add("arjun")
print(a) # a is untouched

Output

{'alex', 'riya', 'maya'}
{'alex', 'riya', 'maya'}

See how the first print already shows β€œmaya” inside a, even though we only added it to b? That is the shared-set trap. With copy(), the change to c left a alone.

❓ Asking Questions: issubset() and issuperset()

Sometimes you do not want to change a set. You just want a yes-or-no answer about how two sets relate.

The issubset() method asks: are all of my items also inside the other set? The issuperset() method asks the opposite: does my set contain all of the other one’s items?

This checks whether a small group of names is fully contained in a bigger group.

free_users = {"alex", "riya", "arjun", "maya"}
trial_users = {"riya", "maya"}
print(trial_users.issubset(free_users))
print(free_users.issuperset(trial_users))
print(free_users.issubset(trial_users))

Output

True
True
False

The first line is True because every trial user is also a free user. The second is True because the free-user set holds all the trial users. The third is False because the big set is not contained inside the small one.

These two are just mirror images of each other. β€œA is a subset of B” means the same thing as β€œB is a superset of A”.

πŸ—‚οΈ The Methods at a Glance

Here is the whole set of tools side by side, so you can pick the right one fast.

Method What it does If the item is missing
add(x) Adds one item Not applicable
update(items) Adds many items at once Not applicable
remove(x) Removes one item Raises an error
discard(x) Removes one item Does nothing, no error
pop() Removes and returns some item Errors on an empty set
clear() Removes everything Not applicable
copy() Makes a separate copy Not applicable

⚠️ Common Mistakes

A few slips trip people up again and again.

  • Using remove() on an item that might not be there. It crashes with a KeyError. Use discard() when you are unsure.
  • Expecting pop() to take from the front or the back. A set has no order, so pop gives you no promise about which item you get.
  • Writing b = a and thinking you made a copy. You did not. Both names point at the same set. Use a.copy() for a real, separate set.
  • Thinking an empty set prints as {}. It prints as set(). The empty curly braces are reserved for an empty dictionary.

Here is the copy mistake in code form. Assume users is a set you already built.

users = {"alex", "riya"}
# ❌ Avoid: shares the same set, edits leak across
saved = users
saved.clear() # users is now empty too!
# βœ… Good: independent copy, the original stays safe
saved = users.copy()
saved.clear() # users is untouched

βœ… Best Practices

Small habits that keep your set code clean.

  • Use discard() by default when removing. It will not crash on a missing item.
  • Use update() instead of a loop of add() calls when you have many items to add. It is shorter and clearer.
  • Always use copy() when you need a separate set you can change without touching the original.
  • Pick issubset() or issuperset() to compare sets instead of writing your own loops. They read like plain English and run fast.

🧩 What You’ve Learned

A quick recap of the tools you now have.

  • βœ… add() puts in one item, update() adds many at once.
  • βœ… remove() crashes on a missing item, while discard() stays quiet.
  • βœ… pop() removes and returns some item, but you do not choose which.
  • βœ… clear() empties a set, and an empty set prints as set().
  • βœ… copy() gives a real separate set, so edits do not leak back to the original.
  • βœ… issubset() and issuperset() answer yes-or-no questions about how two sets relate.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What happens when you call remove() with an item that is not in the set?

    Why: remove() raises a KeyError on a missing item; use discard() if you want no error.

  2. 2

    You need to add several names to a set in one call. Which method fits best?

    Why: update() takes a collection and adds all of its items at once, while add() handles only one.

  3. 3

    How does an empty set print in Python?

    Why: An empty set prints as set(), since {} is reserved for an empty dictionary.

  4. 4

    If trial_users.issubset(free_users) is True, what else is also True?

    Why: Subset and superset are mirror images: A subset of B means the same as B superset of A.

πŸš€ What’s Next?

You can now build sets and reshape them however you like. Next we move to a structure that stores pairs of keys and values. It is perfect when a plain set is not enough.

Introduction to Dictionaries

Share & Connect