Python Set Methods
Table of Contents + β
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 changeprint(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 errorlikes.discard("alex") # this one is there, so it goesprint(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: alexleft: {'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 setb = ab.add("maya")print(a) # a changed too!
# β
Good: copy() gives a real separate setc = a.copy()c.add("arjun")print(a) # a is untouchedOutput
{'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
TrueTrueFalseThe 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 aKeyError. Usediscard()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 = aand thinking you made a copy. You did not. Both names point at the same set. Usea.copy()for a real, separate set. - Thinking an empty set prints as
{}. It prints asset(). 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 acrosssaved = userssaved.clear() # users is now empty too!
# β
Good: independent copy, the original stays safesaved = 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 ofadd()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()orissuperset()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, whilediscard()stays quiet. - β
pop()removes and returns some item, but you do not choose which. - β
clear()empties a set, and an empty set prints asset(). - β
copy()gives a real separate set, so edits do not leak back to the original. - β
issubset()andissuperset()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
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
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
How does an empty set print in Python?
Why: An empty set prints as set(), since {} is reserved for an empty dictionary.
- 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.