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.
| Method | Syntax | Description |
|---|---|---|
| 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.
| Method | Syntax | Description |
|---|---|---|
| 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.
Python Sets
Master sets in Python. Learn to store unique values, execute intersections, unions, differences, and understand the performance benefits of hashing.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.