Sets are an unordered collection of unique elements. This means that a set cannot contain duplicate values. Sets are mutable, allowing you to add and remove elements, but the elements themselves must be immutable (like numbers, strings, or tuples). Sets are defined by enclosing elements in curly braces {} or by using the set() constructor.
Creating Sets
python# An empty set (IMPORTANT: {} creates an empty dictionary, use set() for empty set) empty_set = set() # A set of numbers (duplicates are automatically removed) numbers_set = {1, 2, 3, 2, 1, 4} print(numbers_set) # Output: {1, 2, 3, 4} (order is not guaranteed) # A set of strings fruits_set = {"apple", "banana", "cherry"} print(fruits_set) # Creating a set from a list list_to_set = set(["a", "b", "c", "a"]) print(list_to_set) # Output: {'a', 'b', 'c'} # Sets cannot contain mutable items like lists or dictionaries # invalid_set = {1, [2, 3]} # This would raise a TypeError
Adding and Removing Elements
**1.
Adding elements:
**
set.add(item): Adds a single element to the set.set.update(iterable): Adds multiple elements from an iterable (e.g., list, tuple, string) to the set.
pythonmy_set = {1, 2, 3} my_set.add(4) print(my_set) # Output: {1, 2, 3, 4} my_set.add(1) # Adding an existing element does nothing print(my_set) # Output: {1, 2, 3, 4} my_set.update([5, 6, 7]) print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7} my_set.update({7, 8, 9}) # Can update with another set print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}
**2.
Removing elements:
**
set.remove(item): Removes the specified item. Raises aKeyErrorif the item is not found.set.discard(item): Removes the specified item if it is present. Does not raise an error if the item is not found.set.pop(): Removes and returns an arbitrary element from the set (since sets are unordered, you don't know which item will be removed).set.clear(): Removes all elements from the set.
pythonmy_set = {10, 20, 30, 40} my_set.remove(20) print(my_set) # Output: {10, 30, 40} my_set.discard(10) # 10 is present print(my_set) # Output: {30, 40} my_set.discard(99) # 99 is not present, no error print(my_set) # Output: {30, 40} popped_item = my_set.pop() # Removes an arbitrary item (e.g., 30 or 40) print(f"Popped: {popped_item}, Remaining: {my_set}") my_set.clear() print(my_set) # Output: set()
Set Operations
Sets are powerful for performing mathematical set operations:
- Union (
|orset.union()): Returns a new set containing all unique elements from both sets. - Intersection (
&orset.intersection()): Returns a new set containing elements common to both sets. - Difference (
-orset.difference()): Returns a new set with elements in the first set but not in the second. - Symmetric Difference (
^orset.symmetric_difference()): Returns a new set with elements in either set, but not in both.
pythonset_a = {1, 2, 3, 4} set_b = {3, 4, 5, 6} print(f"Union (A | B): {set_a | set_b}") # Output: {1, 2, 3, 4, 5, 6} print(f"Intersection (A & B): {set_a & set_b}") # Output: {3, 4} print(f"Difference (A - B): {set_a - set_b}") # Output: {1, 2} print(f"Symmetric Difference (A ^ B): {set_a ^ set_b}") # Output: {1, 2, 5, 6}
Other Useful Set Methods
len(set): Returns the number of items.item in set: Checks for membership (returnsTrueorFalse). This is very efficient for sets.set.issubset(other_set): Checks if all elements of the set are inother_set.set.issuperset(other_set): Checks if all elements ofother_setare in the set.
pythonlarge_set = {1, 2, 3, 4, 5} small_set = {2, 3} print(f"Length of large_set: {len(large_set)}") # Output: 5 print(f"3 in large_set: {3 in large_set}") # Output: True print(f"small_set is a subset of large_set: {small_set.issubset(large_set)}") # Output: True print(f"large_set is a superset of small_set: {large_set.issuperset(small_set)}") # Output: True
Sets are ideal for tasks where you need to store unique items and perform efficient membership tests, or when you need to perform mathematical set operations like finding common elements or differences between collections.
Key Takeaways:
- Sets are unordered collections of unique, immutable elements, defined with
{}orset(). - Duplicates are automatically removed upon creation or addition.
- Add elements with
add()orupdate(); remove withremove(),discard(),pop(), orclear(). - Perform set operations like union (
|), intersection (&), difference (-), and symmetric difference (^). - Useful for membership testing (
in) and checking relationships between collections (issubset,issuperset).