Python Set Methods Cheat Sheet

Complete guide to Python set operations. Learn how to add, remove, and perform mathematical set operations like unions and intersections.

Modifying Sets

Common methods to insert, delete, or clean elements within a set.

MethodSyntaxDescription
add()my_set.add(item)Adds an element to the set. Has no effect if element is already present.
remove()my_set.remove(item)Removes the specified element. Raises a KeyError if the element is not found.
discard()my_set.discard(item)Removes the specified element if present. Does not raise an error if not found.
pop()my_set.pop()Removes and returns an arbitrary element from the set. Raises KeyError if empty.
clear()my_set.clear()Removes all elements from the set, leaving it empty.

Mathematical Set Operations

Operations comparing sets or computing intersections, unions, and differences.

MethodSyntaxDescription
union()set1.union(set2)Returns a new set containing all unique elements from both sets.
intersection()set1.intersection(set2)Returns a new set with elements common to both sets.
difference()set1.difference(set2)Returns a new set with elements in set1 but not in set2.
symmetric_difference()set1.symmetric_difference(set2)Returns elements in either set1 or set2, but not both.
issubset()set1.issubset(set2)Returns True if all elements of set1 are in set2.
issuperset()set1.issuperset(set2)Returns True if all elements of set2 are in set1.

Frequently Asked Questions

What is the difference between remove() and discard()?

remove() raises a KeyError if the element is not present, whereas discard() does nothing and terminates successfully.

Can sets contain mutable elements?

No, elements in a set must be hashable (immutable), so you cannot store lists or dictionaries inside a set.

Keep Learning

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.