Python Set Method

Python Set Methods

Python provides various built-in methods to perform operations on sets. Below is a list of common `set` methods with examples.

Common Set Methods

Method Description
add(x) Adds element `x` to the set.
remove(x) Removes `x` (Raises error if not found).
discard(x) Removes `x` (No error if not found).
pop() Removes a random element.
clear() Removes all elements from the set.
union(set2) Returns the union of two sets.
intersection(set2) Returns the intersection of two sets.
difference(set2) Returns elements in this set but not in `set2`.
symmetric_difference(set2) Returns elements not in both sets.

Examples of Set Methods

1. Adding & Removing Elements

            
# Creating a set
numbers = {1, 2, 3}

# Adding an element
numbers.add(4)
print(numbers)  # Output: {1, 2, 3, 4}

# Removing an element
numbers.remove(2)
print(numbers)  # Output: {1, 3, 4}

# Discarding an element (No error if not found)
numbers.discard(5)  # No error
            
        

2. Set Operations

            
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

# Union (A | B)
print(A.union(B))  # Output: {1, 2, 3, 4, 5, 6}

# Intersection (A & B)
print(A.intersection(B))  # Output: {3, 4}

# Difference (A - B)
print(A.difference(B))  # Output: {1, 2}

# Symmetric Difference (A ^ B)
print(A.symmetric_difference(B))  # Output: {1, 2, 5, 6}
            
        

3. Clearing & Popping Elements

            
numbers = {10, 20, 30, 40}

# Removing a random element
numbers.pop()
print(numbers)  # Output: {20, 30, 40} (random element removed)

# Clearing the set
numbers.clear()
print(numbers)  # Output: set()
            
        

When to Use Sets?

  • To store unique values efficiently.
  • For fast membership testing (e.g., x in set).
  • To perform set operations like union, intersection, and difference.