+91 81900 98289

Set Methods

This Set Methods lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

add inserts one value. discard removes a value and stays quiet if it was already absent. remove raises KeyError when the value is missing.

union, intersection, and difference return a new set. The methods that end in _update change the set you call.

Example 1: Start here

discard is the safer delete when you are not sure the value is present.

skills = {"Python"} # a dictionary; each key has one value skills.add("SQL") skills.discard("Git") print(skills)

Example 2: Union and difference

The bar adds sets. The minus sign removes items.

print({"Python", "SQL"} | {"Git"}) # this operator works on the bits of the number print({"Python", "SQL"} - {"SQL"})

Example 3: Subset

<= asks if every item on the left is also on the right.

print({"SQL"} <= {"Python", "SQL"}) # a comparison is True or False

Example 4: Update in place

update adds many items at once.

skills = {"Python"} # a dictionary; each key has one value skills.update(["SQL", "Git"]) # copy those keys into this dictionary print(skills)
discard is the safer delete when you are not sure the value is present.
Call Now 81900 98289