# .css-fhxb3m{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;}.css-9a49z0{margin-right:0.5rem;height:2.5rem;width:2.5rem;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;overflow:hidden;border-radius:9999px;}  Prahlad Inala

Follow

Follow # Sets in Python

·Jul 9, 2021·

## What are Sets in Python?

Sets are collections of unique elements, which means an element is present only once in a set.

They are defined using the curly bracket syntax: my_set={elements}

We can add a new element to the set. but, we can't add an existing element to the set.

## union()

This method creates a new set with all elements in both sets and removes the duplicate elements. In mathematics, we know A∪B(A union B) is the same procedure. syntax:1st_set.union(2nd_set)

### Example

``````my_set1={1,2,5,0}
my_set2={1,2,3,4}
all_elements=my_set1.union(my_set2)
print(all_elements)
#{0, 1, 2, 3, 4, 5}
``````

## intersection()

This method creates a new set with only those elements which are present in both sets. syntax:1_set.intersection(2nd_set)

### Example

``````x = {"python", "git", "django"}
z = x.intersection(y)
print(z)
#python
``````

## difference()

This method removes the common elements and gives the remaining elements as output. syntax:1st_set.difference(2nd_set)

### Example

``````x = {"python", "git", "django"}
z = x.difference(y)
print(z)
#{'django', 'git'}
``````

This method removes the specified element from the set. syntax:variable_set.discard(element)

### Example

``````x = {"python", "git", "django"}
print(x)
#{'python', 'django'}
``````

## copy()

This method returns the copy of the specified set. syntax: existing_set.copy()

### Example

``````x = {"python", "git", "django"}
y= x.copy()
print(y)
#{'python', 'git', 'django'}
``````

## Converting a list to a set

A list can be converted to a set using a built-in (set) function

### Example

``````my_list=[1,2,3,4,1,2,3,4]
my_set=set{my_set}
print(my_set)
#{1,2,3,4}
``````

Note: A set can be converted into the list using a built-in (list) function