Home / Fundamentals

# Python Set Methods

A set in Python is a collection of unique elements. Sets are mutable, which means that you can add or remove elements from a set after it has been created. Python provides several built-in methods for working with sets, which allow you to perform common set operations such as adding and removing elements, finding the intersection or union of sets, and more.

Here is a list of some common set methods in Python, along with brief descriptions and code examples:

Adds an element to the set. If the element is already present in the set, it is ignored.

```# Create a set
my_set = {1, 2, 3}

# Add an element to the set

# Print the set
print(my_set)  # Output: {1, 2, 3, 4}
```

## remove()

Removes an element from the set. If the element is not present in the set, a KeyError is raised.

```# Create a set
my_set = {1, 2, 3}

# Remove an element from the set
my_set.remove(2)

# Print the set
print(my_set)  # Output: {1, 3}
```

## union()

Returns the union of two sets, which is the set of all elements that are present in either set.

```# Create two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Get the union of the sets
union_set = set1.union(set2)

# Print the union set
print(union_set)  # Output: {1, 2, 3, 4, 5}

## intersection()
Returns the intersection of two sets, which is the set of all elements that are present in both sets.
```python
# Create two sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}

# Get the intersection of the sets
intersection_set = set1.intersection(set2)

# Print the intersection set
print(intersection_set)  # Output: {2, 3}
```

## difference()

Returns the difference of two sets, which is the set of all elements that are present in the first set but not in the second set.

```# Create two sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}

# Get the difference between the sets
difference_set = set1.difference(set2)

# Print the difference set
print(difference_set)  # Output: {1}
```

## issubset()

Returns True if the set is a subset of another set, and False otherwise.

```# Create two sets
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4}

# Check if set1 is a subset of set2
is_subset = set1.issubset(set2)

# Print the result
print(is_subset)  # Output: True
```

## issuperset()

Returns True if the set is a superset of another set, and False otherwise.

```# Create two sets
set1 = {1, 2, 3}
set2 = {1, 2}

# Check if set1 is a superset of set2
is_superset = set1.issuperset(set2)

# Print the result
print(is_superset)  # Output: True
```

## pop()

Removes and returns a random element from the set. If the set is empty, a KeyError is raised.

```# Create a set
my_set = {1, 2, 3}

# Pop an element from the set
element = my_set.pop()

# Print the element and the set
print(element)  # Output: 1
print(my_set)  # Output: {2, 3}
```

## clear()

Removes all elements from the set.

```# Create a set
my_set = {1, 2, 3}

# Clear the set
my_set.clear()

# Print the set
print(my_set)  # Output: set()
```