# Operations on Set Objects in Python with Examples

Hi Learner! In this article, we are going to learn to find the common characters of two strings using sets in Python. Let us see how simple it can be to find the common characters of two strings using a simple set operation.

## Sets in Python

A set is a collection of elements without any duplicate elements and order. We use curly br a set. Just like * list()* method, we have a

*method to declare a set object.*

**set()****Note**:-

Since we represent both set and dictionary using **{}** in Python, we cannot declare an empty dictionary using **{}**. We make use of the * set()* method to do the same.

Now, let us learn about a few operations that we can perform on * set *objects.

### 1.Union |

Let * set1* and

*be two set objects containing some elements. Using union operator*

**set2****|**between the two set objects

*the union of*

**returns***and*

**set1***i.e. a set containing both the*

**set2***elements in*

**unique***and*

**set1***.*

**set2**Let us now understand with an example.

set1 = set("Monty") set2 = set("Python3") print(set1) print(set2) print(set1|set2)

#### Output:

{'o', 'n', 't', 'y', 'M'} {'o', 'n', 't', '3', 'y', 'h', 'P'} {'o', 'n', 't', '3', 'y', 'h', 'M', 'P'}

We can notice that * set1|set2* returned a set of elements from both

*and*

**set1***objects.*

**set2**### 2. Difference –

Difference operator – between the two set objects * returns* the elements present in

*and not in*

**set1***.*

**set2**Example:

set1 = set('Python3') set2 = set([1,2,3,'t','n']) print(set1) print(set2) print(set1-set2)

#### Output:

{'P', 't', 'y', 'h', 'n', 'o', '3'} {'t', 1, 2, 3, 'n'} {'P', 'y', 'h', 'o', '3'}

### 3. Intersection &

Intersection operator + between the two set objects * returns* the elements present in both

*and*

**set1***.*

**set2**Example:

set1 = set("Mathematics2") set2 = set(['s','c','i','e','n','c','e',2]) print(set1) print(set2) print(set1&set2)

#### Output:

{'m', 'a', 'c', 't', 'h', 'e', 's', '2', 'i', 'M'} {2, 'c', 'n', 'e', 's', 'i'} {'s', 'c', 'i', 'e'}

### 4. Symmetric Difference ^

Symmetric operator ^ between the two set objects * returns* the elements present in

**either**in

*or*

**set1***but*

**set2****not**both

*and*

**set1***.*

**set2**Example:

set1 = set("Mathematics2") set2 = set("Science2") print(set1) print(set2) print(set1^set2)

#### Output:

{'m', 'a', 's', 'e', 'h', 'c', '2', 't', 'i', 'M'} {'n', 'e', 'c', 'S', '2', 'i'} {'m', 's', 'h', 't', 'M', 'a', 'n', 'S'}

Hurrah! we have learned to perform some cool operations on sets.

Thanks for reading this article. I hope you have found this article helpful.

Also, do check our other articles related to sets in Python below:

## Leave a Reply