In this tutorials, we will see in-depth details about **Python Set Data Structure**.

## Python Set Data Structure:

Python Set represents a group of unique elements. If you wish to represent a group of unique elements into a single entity, then you can go with Python Set.

### Characteristics of Set in Python:

- The Set doesn’t allow duplicate elements.
- It doesn’t preserve the insertion order.
- We can store the heterogeneous elements in a Set.
- Set objects are mutable, hence we can change the elements in a Set whenever we need it.

## Creating Set :

You can create a Set using curly braces {} and set() function.

**Example:**

```
#set
s = {10,20,30,40}
print(type(s))
#set with hererogenious elements
s2 = {10,'A',"B",10.5}
print(type(s2))
#set with character elements
values = ['A','B','C','D']
s3 = set(values)
print(type(s3))
#set created uisng set() function
s4 = set(range(5))
print(type(s4))
```

**Output:**

```
<class 'set'>
<class 'set'>
<class 'set'>
<class 'set'>
```

Creating empty set is something tricky, we do not use empty curly braces {} to create empty Set, you do so, it will create python directory for you instead of empty Set. If you really want *empty* set go for *set()* function.

```
#It will give dict type
s = {}
print(type(s))
# It will create an emtpy set
s2=set()
print(type(s2))
```

**Output:**

```
<class 'dict'>
<class 'set'>
```

## Adding elements to Set:

You can add elements to set using add() or update() functions. add() function is used to add a single element at a time, whereas update() function is used to add multiple elements at a time.

update() function can take list, tuple, string as an argument and will add it to the set.

```
s1=set()
s1.add(10)
s1.add(20)
print(s1)
#Adding multiple elements at a time
list = ['H','E','L','L','O']
s1.update(list)
print("Updated Set : ",s1)
#Adding elements with range() function
s1.update(range(1,5),range(5,10,1))
print("Updated with range : ",s1)
```

**Output:**

As we discussed earlier, Python Set doesn’t preserve insertion order, we can’t expect the outcome as we insert.

```
{10, 20}
Updated Set : {'L', 'O', 10, 'E', 'H', 20}
Updated with range : {1, 2, 3, 4, 5, 'L', 'O', 6, 7, 10, 8, 9, 'E', 'H', 20}
```

## Removing Elements from Set:

You can remove an element from Set using 4 different functions.

- remove()
- discard()
- pop() and
- clear()

### remove()

remove(x) function is used to remove a specific element from the Set. If the given element is not found in the set, it will throw KeyError.

```
s1={10,20,30,40,50}
s1.remove(20)
print("After Removing 20 : ",s1)
#Removing unknown element
s1.remove(70)
```

**Output:**

```
After Removing 20 : {40, 10, 50, 30}
Traceback (most recent call last):
File ".\sample.py", line 6, in <module>
s1.remove(70)
KeyError: 70
```

### discard(x)

It removes the given element from the Set. The only difference between remove() and discard() is – If the given element not found in the Set, remove() function throw KeyError, whereas discard() doesn’t give any error.

```
s1={10,20,30,40,50}
s1.discard(50)
print("After discard 50 : ",s1)
#discard unknown element
s1.discard(100)
print("After discard 100 : ",s1)
```

**Output:**

```
After discard 50 : {40, 10, 20, 30}
After discard 100 : {40, 10, 20, 30}
```

### pop()

pop() removes and returns some random element from the Set.

```
s1 = {1,'a',2,4,5,8,9}
print("poped element : ",s1.pop())
print("After pop() the set wil be : ")
print(s1)
```

**Output:**

```
poped element : a
After pop() the set wil be :
{1, 2, 4, 5, 8, 9}
```

### clear()

**clear()** function is used to remove all elements from the Set.

```
s1 = {1,'a',2,4,5,8,9}
print("Elements in Set: ",s1)
s1.clear()
print("After clearing ")
print(s1)
```

**Output:**

```
Elements in Set: {1, 2, 4, 5, 8, 9, 'a'}
After clearing
set()
```

## Python Set operations:

Set can be used in mathematical operations like union, intersection, difference and symmetric difference. Pythons gave different functions to handle these operations.

### Union():

Let’s consider the below two sets:

```
s1 = {10,20,30,40,50}
s2 = {60,70,50,80,10}
```

union of **s1 **and **s2 **will produce a new set of all elements from both s1 and s2 sets. This operation also achieved using | (or) operator.

**Example:**

```
s1 = {10,20,30,40,50}
s2 = {60,70,50,80,10}
print("union of s1, s2 : ",s1.union(s2))
print("s1 | s2 : ",s1|s2)
```

**Output:**

```
union of s1, s2 : {70, 40, 10, 80, 50, 20, 60, 30}
s1 | s2 : {70, 40, 10, 80, 50, 20, 60, 30}
```

### intersection():

The intersection of two different sets (**s1,s2**) will produce a new set of elements which are common in both sets. It is also achieved using & (and) operator.

**Example:**

```
s1 = {10,20,30,40,50}
s2 = {60,70,50,80,10}
print("intersection of s1, s2 : ",s1.intersection(s2))
print("s1 & s2 : ",s1&s2)
```

**Output:**

```
intersection of s1, s2 : {10, 50}
s1 & s2 : {10, 50}
```

### difference():

difference() function returns the elements which are present in **s1** but not in **s2**. It is also achieved using – (minus) operator.

**Example:**

```
s1 = {10,20,30,40,50}
s2 = {60,70,50,80,10}
print("difference of s1, s2 : ",s1.difference(s2))
print("s1 - s2 : ",s1-s2)
```

**Output:**

```
difference of s1, s2 : {40, 20, 30}
s1 - s2 : {40, 20, 30}
```

### symmentric_difference():

The symmentric_difference function returns the elements which are present in either s1 or s2 but not in both. It can be also achieved using **‘^’** operator.

**Example:**

```
s1 = {10,20,30,40,50}
s2 = {60,70,50,80,10}
print("symmetric_difference of s1, s2 : ",s1.symmetric_difference(s2))
print("s1 ^ s2 : ",s1^s2)
```

**Output:**

```
symmetric_difference of s1, s2 : {80, 20, 70, 40, 60, 30}
s1 ^ s2 : {80, 20, 70, 40, 60, 30}
```

### Set Membership operations:

We can apply membership operators on python set data structure. The membership operators – **in, not:** are used to test whether a given element exists in the set or not.

**Example:**

```
s1 = {10,20,30,40,50}
print("is 10 in s1 ? ", 10 in s1)
print("is 60 in s1 ? ", 60 in s1)
```

**Output:**

```
is 10 in s1 ? True
is 60 in s1 ? False
```

**Examples for Python Set:**

**References:**

Happy Learning ðŸ™‚

## Leave A Comment