*Stuck trying to use Python set operations? Do you want to know how to use them? This tutorial gives you a basic understanding of set operations in Python.*

In this tutorial, we'll look at set operations in Python and other operations performed on sets. In addition, we look at the different methods for sets and examples of set operations in Python. look at thatArticle for a deeper dive into combinatorics with Python.

A set is a collection of unordered elements. Each element must be unique and immutable. However, a lot itself is changeable.

You can add or remove items from sets. You can also perform mathematical operations on them such as B. Union, intersection and difference.

The concept of a set has been explicitly translated from mathematics into programming languages like Python. With that have come some extremely helpful methods, such as:`Union()`

,`Overlap()`

, And`Difference()`

, also directly translated from mathematics.

Sets are not simply a fundamental concept in mathematics. During your programming career, you will likely encounter a variety of challenges that can be solved much more quickly by using sets.

If you are an absolute beginner in Python, we recommend you give it a trythis track. If you are a beginner with some Python knowledge, check out the coursePython Basics Part 3, which covers the basics of variables, lists, conditional statements, loops, and functions.

## Sets and set operations in Python

A set is defined by enclosing each element (i.e. elements) in braces and separating them with a comma or using the built-in`Sentence()`

Method. It can contain an unlimited number of elements of different categories (integer, float, tuple, string, etc.).

However, a sentence cannot contain modifiable elements such as lists, sentences, or dictionaries. Visit this article toLearn about the differences between lists, tuples, and sets.LearnPython.comis an incredible platform to help you get started with Python.

Empty sets can be a little tricky to use in Python. In Python, empty braces result in an empty dictionary; However, we cannot use them to initialize an empty set. Instead we use the`Sentence()`

Function with no arguments to create a set with no elements.

Check out the following code to understand these concepts:

# A set of integersint_set = {10, 20, 30, 40, 50}# A set of mixed data types mixed_set = {9, "This is a set item", (1, 2)}# All set items are uniquemy_set = { 1, 2 , 3, 1, 3, 3}print(my_set) # Output: {1, 2, 3}# From a listmy_set = set([1, 2, 3, 2, 4, 5 , 5])print(my_set) # Output: {1, 2, 3, 4, 5}

### Modifying a set in Python

Indexing and partitioning cannot be used to access or update an element of a set. The set data type does not support this because sets are not ordered.

The`add to()`

method is used to add a single element, and the`To update()`

method is used to update multiple components. Tuples, lists, strings, and other sets can be passed to`To update()`

Method. Duplicates are avoided at all costs.

The following code illustrates these examples.

# Set initializemy_set = {11, 60}# Add an item to the set# Output: {11, 21, 60}my_set.add(21)print(my_set)# Add more than one item to the set# Output: { 8, 11 , 13, 20, 21, 60}my_set.update([20, 13, 8])print(my_set)

### Remove items from a set

The methods`discard()`

And`removed()`

are used to delete a specific element from a set. They are identical with only one difference. The`discard()`

method leaves the set unchanged if the item does not exist in the set. The`removed()`

method, on the other hand, returns an error if the item is not present in the set.

The use of these functions is demonstrated in the following example.

# Initialize a setmy_set = {10, 20, 30, 40, 50}print(my_set)# Discard an elementmy_set.discard(40)print(my_set) # Output: {10, 20, 30, 50}# Remove an elementmy_set. remove(60) # Key error!

We can use those too`Pop()`

Method of removing and returning an item. However, there is no way of knowing which element will be inserted since the set is an unordered data type. It's absolutely random!

Note that the`clear()`

Method is used to delete all elements from a set.

# Initialize a setmy_set = set("LearnPython")# Pop an element print(my_set.pop()) # Output: random element# Clear setmy_set.clear() print(my_set) # Output: set()

In Python, most, but not all, set operations are performed in one of two ways: by an operator or by a method. Before we look at how different set operations work in Python, it's important to understand the difference between an operator and a method.

In Python, a method is similar to a function except that it is bound to an object. When we invoke a method on an object, it may or may not affect that object—a set, in this case. It's worth noting that each operator corresponds to a specific Python special function. So they both accomplish the same thing, but have different syntax requirements.

Python supports many set operations including union, intersection, difference, and symmetric difference. Let's look at some examples of set operations in Python.

## Python union operation with example

The union of two sets is the set of all elements without duplicates that are in either or both sets. In Python you can either use the`Union()`

method or the`|`

Syntax to find the union. Let's look at a Python union example.

Use of`|`

Operator:

# define the two sets first_set = {1, 5, 7, 4, 5}second_set = {4, 5, 6, 7, 8}# create the union of the two sets new_set = first_set | second_setprint(new_set) # output: {1, 2, 3, 4, 5, 6, 7, 8}

Running the above code will create two sets:`first set`

And`second_set`

. Then the union operator creates a`new_set`

with all the unique elements from the`first set`

and the`second_set`

.

The same is achieved with the`Union()`

Method:

new_set = first_set.union(second_set)

Since the union consists of the elements of both sets, it is symmetric. So,`first_set.union(second_set)`

gives the same sentence as`second_set.union(first_set)`

.

## Python intersection operation with example

The intersection of two sets is the set of all elements common to both sets. In Python you can either use the`Overlap()`

method or the & operator to find the intersection. Here are some examples of Python cuts:

Using the & operator:

# define the two setsfirst_set = {1, 5, 7, 4, 5}second_set = {4, 5, 6, 7, 8}# create the intersection of the two setsnew_set = first_set & second_setprint(new_set) # output: {4 , 5}

Running the above code will create two sets:`first set`

And`second_set`

. Then the intersection operator produces a`new_set`

with all the unique elements from the`first set`

and the`second_set`

.

The same is achieved with the`Overlap()`

Method:

new_set = first_set.intersection(second_set)

Because the intersection method produces a set of elements common to both sets, it is symmetric. So,`first_movement.intersection(second_movement)`

gives the same sentence as`second_movement.intersection(first_movement)`

.

## Python Set Difference Operation with example

The difference between the two sets is the set of all elements that are present in the first set but not in the second. With Python you can either use the`Difference()`

method or operator to do this. Let's look at some examples of Python set differences.

Using the - operator:

# Definition of the two setsfirst_set = {1, 5, 7, 4, 5}second_set = {4, 5, 6, 7, 8}# Formation of the difference between the two setsnew_set = first_set - second_setprint(new_set) # Output: {1 , 2, 3}

You can also use the`Difference()`

Method:

# Initialize difference of two sets# A and Bfirst_set = {1, 2, 3, 4, 5}second_set = {4, 5, 6, 7, 8}# Create difference between the two setsnew_set = second_set.difference(first_set) print( new_set) # output: {6, 7, 8}

As shown in the example, the**Difference operator is not symmetric**. Which quantity you name first is important and influences the outcome of the`new_set`

.

## Leverage Python set operations

In this tutorial you learned how to define set operations in Python. We also became familiar with the functions, operators, and methods used to work with sets. If you want to learn more about Python sets, e.g. B. How to get the symmetric difference visit the article “Python Set Operations and More: Everything you need to know about Python sets.“