# Set Operations in Python

# Set Operations in Python

### In this code snippet, we'll discuss how to perform various operations on set in Python using inbuilt functions and operators.

Join the DZone community and get the full member experience.

Join For FreeSet theory is a branch of mathematical logic that studies sets, which informally are collections of objects. Although any type of object can be collected into a set, set theory is applied most often to objects that are relevant to mathematics. The language of set theory can be used to define nearly all mathematical objects. [wiki]

#### A set in Python is a collections of unique elements. Get your pen and paper and draw those venn diagrams to learn about set operations.

A set is a Many that allows itself to be thought of as a One.

~ Georg Cantor

We will use Python to find the:

- Union
- Intersection
- Difference
- Symmetric Difference

of two sets.

Here, I have taken two sets of numbers and have written code to find out the above operations in two ways.

- Using operators.
- Using inbuilt functions.

`xxxxxxxxxx`

`# Date: 27th Jun 2020 by Manas`

`# Lets learn Set Theory in Python`

`# Few Operations on Sets`

`# Let's take two sets`

`first_set = {11, 21, 31, 41, 51}`

`second_set = {11, 61, 71, 81, 31}`

`print('First Set : ' + str(first_set))`

`print('Second Set : ' + str(second_set))`

`# The basic operations are:`

`# 1. Union of Sets`

`print('\nUNION of the two sets are (Both in first and second)')`

`print(set(first_set) | set(second_set))`

`# inbuilt function`

`print(first_set.union(second_set))`

`# 2. Intersection of sets`

`print('\nIntersection of the two sets are (common to both)')`

`print(set(first_set) & set(second_set))`

`# inbuilt function`

`print(first_set.intersection(second_set))`

`# 3. Difference of two sets`

`print('\nDifference of the two sets are (in first but not in second) ')`

`print(set(first_set) - set(second_set))`

`# inbuilt function`

`print(first_set.difference(second_set))`

`# 4. Symmetric difference of two sets`

`print('\nSymmetric Difference of the two sets are (excluding the common element of both) ')`

`print(set(first_set) ^ set(second_set))`

`# inbuilt function`

`print(first_set.symmetric_difference(second_set))`

Opinions expressed by DZone contributors are their own.

## {{ parent.title || parent.header.title}}

{{ parent.tldr }}

## {{ parent.linkDescription }}

{{ parent.urlSource.name }}