Flat_Eric Contemplating Data Type Conversions

Set Methods

Set Methods

Now that we have the basics down, we’re going to look at the methods that actually make Sets powerful for comparing data. Think of this as "Data Math."

We will use these two sets for our examples:

this_set = {1, 2, 3, 4}
that_set = {3, 4, 5, 6}

1. .difference()

This returns a new set containing items that exist in the first set but NOT in the second. It’s like saying "Give me what's unique to me."

When to use: Use this to find "Missing items," like comparing a list of all students to a list of students who turned in their homework to see who is missing.

2. .discard()

We touched on this briefly, but to reiterate: it removes a specific item from the set. Unlike .remove(), if the item isn't there, it does nothing instead of crashing.

When to use: Use this when you want to clean up data but aren't 100% sure the item exists; it prevents your program from crashing if the item was already gone.

3. .difference_update()

This is the aggressive version of .difference(). Instead of creating a new set, it removes all items from the original set that are also in the other set.

When to use: Use this when you want to permanently "prune" your original set, such as removing a list of "unsubscribed" emails from your main mailing list.

4. .intersection()

This returns a new set with only the items that exist in BOTH sets. It’s the "overlap."

When to use: Use this to find "Common ground," like seeing which skills two different job candidates both have in common.

5. .isdisjoint()

This returns True or False. It asks: "Do these two sets have nothing in common?" If there is even one overlapping item, it returns False.

When to use: Use this for "Conflict checking," such as verifying that a "Restricted Items" list and a "Customer Cart" list have no overlapping items.

6. .issubset()

This asks: "Are all the items in my set also inside the other set?"

When to use: Use this to check for "Requirements," like seeing if a user's "Permissions" set contains all the items required for an "Admin" role.

7. .issuperset()

The opposite of a subset. It asks: "Do I contain all the items of the other set (and potentially more)?"

When to use: Use this from the perspective of the "Container," like checking if your "Inventory" contains everything listed in a "Customer Order."

8. .union()

This returns a new set containing all items from both sets. Remember, sets automatically handle duplicates, so shared items only appear once.

When to use: Use this for "Merging," like combining two different contact lists into one master list while automatically preventing any duplicate contacts.

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course