Last Updated on December 22, 2023 by Ankit Kochar

Python sets are a fundamental data structure that provide a collection of unique elements, making them incredibly useful in various programming scenarios. Set operations in Python allow for efficient manipulation and analysis of sets, enabling developers to perform tasks like intersection, union, difference, and more. Understanding these operations is essential for optimizing code, handling data, and simplifying complex tasks within Python programs.

In this article, we’ll delve into the world of Python set operations, exploring their syntax, functionality, and practical applications. Whether you’re a beginner seeking foundational knowledge or an experienced developer looking to refine your skills, this comprehensive guide aims to provide valuable insights into leveraging set operations effectively in Python.

## What are Sets in Python?

Sets in Python are very much like lists except that their elements are immutable (you cannot change or edit an element of a set after it has been declared). But, you can surely add/delete elements from the set. If it seemed confusing, let me try to summarise:

A set is a mutable, unordered collection of elements, where the elements themselves are immutable. Another feature of a set is that it can contain elements of various types. This implies that you can have a collection of numbers, strings, and even tuples in the same set!

## Python Set Operations

If you remember your high school basic math, you’ll probably recall mathematical set operations like union, intersection, difference, and symmetric difference. Now, the interesting part is we can do the same thing with Python sets.

### Set Union

The union of two sets is the set that contains all of the elements from both sets without duplicates. To find the union of two Python sets, use the union() method or the | syntax.

Here is an example of how to perform a union set operation in python.

set1 = {11, 22, 33} set2 = {33, 54, 75} # Perform union operation using the `|` operator or the `union()` method union_set = set1 | set2 # Or: union_set = set1.union(set2) print(union_set)

**Output:**

`{33, 22, 54, 75, 11}`

**Explanation:** In this example, we have two sets set1 and set2. We can perform a union operation using either the | operator or the union() method, which combines all the elements from both sets and removes any duplicates. The resulting union_set contains all elements from set1 and set2.

### Set Intersection

The intersection of two sets is the set that contains all of the common elements of both sets. To find the intersection of two Python sets, we can either use the intersection() method or & operator.

Here is an example to demonstrate this.

set1 = {11, 22, 33} set2 = {33, 54, 75} # Perform intersection operation using the `&` operator or the `intersection()` method intersection_set = set1 & set2 # Or: intersection_set = set1.intersection(set2) print(intersection_set)

**Output:**

`{33}`

**Explanation:** In this example, we have two sets set1 and set2. We can perform an intersection operation using either the & operator or the intersection() method, which returns a new set that contains only the elements that are common to both set1 and set2. The resulting intersection_set contains only element 33, which is present in both set1 and set2.

### Set Difference

The difference between the two sets is the set of all the elements in the first set that are not present in the second set. To accomplish this, we can either use the difference() function or the – operator in python.

Here is an example to demonstrate this.

set1 = {1, 2, 3, 4, 5} set2 = {3, 4, 5, 6, 7} # Using the difference() method set3 = set1.difference(set2) print(set3) # Using the - operator set4 = set1 - set2 print(set4)

**Output:**

```
{1, 2}
{1, 2}
```

**Explanation:** In this example, we have two sets set1 and set2 with some common elements. We want to get the elements that are present in set1 but not in set2. We can achieve this by using the difference() method or the – operator.

In the first approach, we use the difference() method of set1 and pass set2 as an argument. This returns a new set set3 that contains the elements that are present in set1 but not in set2.

In the second approach, we use the – operator to perform the set difference operation. This is equivalent to using the difference() method. The result is stored in the set4.

### Set Symmetric Difference

The symmetric difference between the two sets is the set containing all the elements that are either in the first or second set but not in both. In Python, you can use either the symmetric difference() function or the ^ operator to achieve this.

Here is an example that demonstrates this.

set1 = {1, 2, 3, 4, 5} set2 = {3, 4, 5, 6, 7} # Using the symmetric_difference() method set3 = set1.symmetric_difference(set2) print(set3) # Using the ^ operator set4 = set1 ^ set2 print(set4)

**Output:**

```
{1, 2, 6, 7}
{1, 2, 6, 7}
```

**Explanation:** In this example, we have two sets set1 and set2 with some common elements. We want to get the elements that are present in either of the sets, but not in both. We can achieve this by using the symmetric_difference() method or the ^ operator.

In the first approach, we use the symmetric_difference() method of set1 and pass set2 as an argument. This returns a new set set3 that contains the elements that are present in either of the sets, but not in both.

In the second approach, we use the ^ operator to perform the set symmetric difference operation. This is equivalent to using the symmetric_difference() method. The result is stored in the set4.

## Other Set Operations in Python

These are not so common but they are useful in seeing how sets are related to each other.

### Issubset

The issubset() operation is used in Python to check whether a set is a subset of another set.

Here’s an example to demonstrate this:

set1 = {1, 2, 3, 4, 5} set2 = {2, 4} # Check if set2 is a subset of set1 print(set2.issubset(set1)) # Check if set1 is a subset of set2 print(set1.issubset(set2))

**Output:**

```
True
False
```

**Explanation:** In this example, we have two sets set1 and set2. We want to check if set2 is a subset of set1. We can do this by calling the issubset() method of set2 and passing set1 as an argument. This returns a boolean value True, which indicates that set2 is a subset of set1.

Next, we check if set1 is a subset of set2 by calling the issubset() method of set1 and passing set2 as an argument. This returns a boolean value False, which indicates that set1 is not a subset of set2.

### Issuperset

The issuperset() operation in Python is used to check whether a set is a superset of another set. A superset is a set that contains all the elements of another set.

Here’s an example to demonstrate this:

set1 = {1, 2, 3, 4, 5} set2 = {2, 4} # Check if set1 is a superset of set2 print(set1.issuperset(set2)) # Check if set2 is a superset of set1 print(set2.issuperset(set1))

**Output:**

```
True
False
```

**Explanation:** In this example, we have two sets set1 and set2. We want to check if set1 is a superset of set2. We can do this by calling the issuperset() method of set1 and passing set2 as an argument. This returns a boolean value True, which indicates that set1 is a superset of set2.

Next, we check if set2 is a superset of set1 by calling the issuperset() method of set2 and passing set1 as an argument. This returns a boolean value False, which indicates that set2 is not a superset of set1.

### Isdisjoint

The isdisjoint() operation in Python is used to check whether two sets have any common elements. If the two sets have no common elements, then they are said to be disjoint.

Here’s an example to demonstrate this:

set1 = {1, 2, 3, 4, 5} set2 = {6, 7, 8} # Check if set1 and set2 are disjoint print(set1.isdisjoint(set2)) set3 = {4, 5, 6} set4 = {6, 7, 8} # Check if set3 and set4 are disjoint print(set3.isdisjoint(set4))

**Output:**

```
True
False
```

**Explanation:** The isdisjoint() method in Python is used to check whether two sets have any common elements. If the two sets have no common elements, then they are said to be disjoint.

Here’s an example to illustrate the isdisjoint() method:

In this example, we have two sets set1 and set2. We want to check if they are disjoint, i.e., they have no common elements. We can do this by calling the isdisjoint() method of set1 and passing set2 as an argument. This returns a boolean value True, which indicates that set1 and set2 are disjoint.

Next, we have two sets set3 and set4. We want to check if they are disjoint or not. We can do this by calling the isdisjoint() method of set3 and passing set4 as an argument. This returns a boolean value False, which indicates that set3 and set4 are not disjoint, since they have a common element 6.

**Conclusion**

Python set operations offer a powerful toolkit for working with collections of unique elements. By harnessing the capabilities of sets and their operations like union, intersection, difference, and more, developers can efficiently handle data, perform comparisons, and simplify complex tasks. These operations not only enhance code readability but also contribute to optimizing performance by utilizing Python’s built-in methods effectively.

As you continue to explore and apply set operations in your Python projects, remember that their versatility extends to various domains, from data manipulation to algorithm design. Mastering these operations will undoubtedly empower you to write cleaner, more concise, and efficient Python code.

## FAQs Related to Python Set Operations

Here are some frequently asked questions on python set operations.

**1. Can a set have duplicate elements?**

No, a set cannot have duplicate elements. If you try to add a duplicate element to a set, it will simply be ignored.

**2. What are the basic set operations in Python?**

The fundamental set operations in Python include:

**Union:**set1 | set2 or set1.union(set2)**Intersection:**set1 & set2 or set1.intersection(set2)**Difference:**set1 – set2 or set1.difference(set2)**Symmetric Difference:**set1 ^ set2 or set1.symmetric_difference(set2)

**3. How do set operations differ from other data structures in Python?**

Sets are distinct due to their unique element property. Unlike lists or tuples, sets do not retain elements in a specific order, and each element exists only once in a set.

**4. When should I use set operations in Python?**

Set operations are particularly useful when dealing with unique collections of data and when performing tasks like finding common elements, eliminating duplicates, or comparing data across multiple sets efficiently.

**5. Are set operations computationally efficient in Python?**

Yes, set operations in Python are optimized for efficiency. These operations leverage hashing techniques, enabling faster computations, especially when working with large datasets, compared to traditional looping approaches.