**Set:**

A set is a sequence data type in python which is an unordered collection of items. Set contains only unique elements (No duplicates) and every element of the set is immutable (cannot be changed).

The elements in the set are immutable, but the set is mutable, we can add or remove elements from the set. Mathematical set operations like Union, intersection, difference, and the symmetric difference can be performed on sets.

**Creation of Sets:**

A set can be created by placing comma-separated elements in curly braces **{ } **or by using the in-built **set()** function. Elements of sets can be of any type, but they should be immutable. Set may contain number,strings,tuples,floats etc. Set cannot contain mutable data types like lists, dictionaries, sets, etc.

**Code:**

## Python Code

```
#valid set with immutable elements
s1 = {1,2,3,"tuf","striver"}
print(s1)
#Invalid set,as it contains mutable elements
#throws error
s2 = {[1,2,3],"india",'kohli'}
print(s2)
```

**Output:**

{1, 2, 3, ‘striver’, ‘tuf’}

Traceback (most recent call last):

File “c:\Users\angaj\Desktop\tuf codes\python_data_types.py”, line 6, in <module>

s2 = {[1,2,3],”india”,’kohli’}

TypeError: unhashable type: ‘list’

An empty set can be created using the set() function. Using curly braces { } creates a empty dictionary. So Always use the set() function to create an empty set.

**Code : **

## Python Code

```
# creating an empty dictonary
s1 = {}
print(type(s1))
# creating an empty set
s2 = set()
print(type(s2))
```

**Output:**

<type ‘dict’>

<type ‘set’>

**Any sequence Data type can be converted into the set using the set() function**

**Code : **

## Python Code

```
# converting list into set
list_to_set = set([1, 2, 3, 3, 4, 5, 6, 68, 91, 19])
print(list_to_set)
# converting tuple into set
tuple_to_set = set((2, 35, 52, 1, 3, 5, 6, 3, 5, 1, 3,))
print(tuple_to_set)
# converting string into set
string_to_set = set("takeuforward")
print(string_to_set)
# converting dictonary into set
dict_to_set = set({'india': 'kohli', 'tuf': 'striver'})
print(dict_to_set)
```

**Output:**

set([1, 2, 3, 4, 5, 6, 19, 68, 91])

set([1, 2, 3, 5, 6, 35, 52])

set([‘a’, ‘e’, ‘d’, ‘f’, ‘k’, ‘o’, ‘r’, ‘u’, ‘t’, ‘w’])

set([‘india’, ‘tuf’])

**Set operations: **

Python sets support the mathematical set operations like union, intersection, difference, and symmetric difference. Let’s look at operations one by one

**Set Union**

Union of Two Sets A and B is a set of all elements from both sets.

In python union of two sets can be found using the **union() **method or using the** ‘ | ‘** operator.

**Code:**

## Python Code

```
A = {1, 2, 3, 4, 5, 6, 7}
B = {6, 7, 8, 9, 10}
# Union of sets A and B using union() method
C = A.union(B)
print(C)
#AUB == BUA
D = B.union(A)
print(D)
#Union of sets A and B using | operator
print(A|B)
```

**Output:**

set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

**Set Intersection : **

The intersection of two sets is the common element in both sets.

In python intersection of two sets can be found using the **intersection() **method or** ‘ & ’** operator

**Code :**

## Python Code

```
A = {1, 2, 3, 4, 5, 6, 7}
B = {6, 7, 8, 9, 10}
# Intersection of sets A and B using intersection() method
C = A.intersection(B)
print(C)
#A∩B == B∩A
D = B.intersection(A)
print(D)
#Intersection of sets A and B using & operator
print(A&B)
```

**Output:**

{6, 7}

{6, 7}

{6, 7}

**Set Difference :**

Let’s take two sets A and B . Difference between set B from set A **(A-B) **is a set of elements that are only in A but not in B. Similarly **(B-A)** means a set of elements that are only in B but not in A.

The difference can be found using the **difference()** method or **‘ – ‘ **operator

**Code :**

## Python Code

```
A = {1, 2, 3, 4, 5, 6, 7}
B = {6, 7, 8, 9, 10}
# Differnce of set B from set A (A-B)
print(A-B)
# Differnce of set A from set B (B-A)
print(B-A)
```

**Output:**

{1, 2, 3, 4, 5}

{8, 9, 10}

**Set Symmetric Difference **

The symmetric difference between sets A and B is a set of elements in A and B but not in both.

Symmetric Difference is nothing but the subtracting intersection of A and B from the Union of A and B.

Symmetric Difference can be found using the **symmetric_difference() **function and **^** operator.

**Code :**

## Python Code

```
A = {1, 2, 3, 4, 5, 6, 7}
B = {6, 7, 8, 9, 10}
# symmetric Difference using symmetric_differnce
print(A.symmetric_difference(B))
# symmetric Difference using ^ operator
print(A ^ B)
# Subtracting Intersection from Union
print((A | B) - (A & B))
```

**Output:**

{1, 2, 3, 4, 5, 8, 9, 10}

{1, 2, 3, 4, 5, 8, 9, 10}

{1, 2, 3, 4, 5, 8, 9, 10}

**Python Set Methods : **

Python provides some methods to deal with the sets. Let’s look at the available methods for set objects.

Method | Description |

add() | Adds a new element to set |

clear() | Removes all the elements from the set. But the set is not deleted. |

copy() | Returns a copy of the set |

difference() | Return the difference of two or more sets as a new set. |

discard() | Removes the element from the set, if the element is a member of the set. If not a member does nothing. |

remove() | Removes an element from the set. If the element is not found raises KeyError. |

intersection() | Returns the intersection of two or more sets as a new set. |

isdisjoint() | Returns True if two sets are disjoint. Disjoint sets are those sets that have no intersection |

issubset() | Returns True if one set is a subset of another else False. |

issuperset() | Returns True if one set is a superset of another, else False. |

pop() | Removes and returns an arbitrary set element. Raises KeyError if the set is empty. |

symmetric_differnce() | Returns the symmetric difference of two sets as a new set. |

union() | Returns the union of sets in a new set. |

### add()

**Code:**

## Python Code

```
A = {1, 2, 3, 4, 5, 6, 7}
# adding new element to set A
print("Set A before adding new element")
print(A)
print("Set A after adding new element")
A.add(35)
print(A)
```

**Output:**

Set A before adding new element

{1, 2, 3, 4, 5, 6, 7}

Set A after adding new element

{1, 2, 3, 4, 5, 6, 7, 35}

**copy**()

**Code **

## Python Code

```
A = {1, 2, 3, 4, 5, 6, 7}
# copying the elements of A into C
C = A.copy()
print("Set C is : ", C)
```

**Output:**

Set C is : {1, 2, 3, 4, 5, 6, 7}

### clear()

**Code:**

## Python Code

```
A = {1, 2, 3, 4, 5, 6, 7}
# removing all the elements of Set A
print("Set A before removing elements")
print(A)
print("Set A after removing all elements")
A.clear()
print(A)
```

**Output:**

Set A before removing elements

{1, 2, 3, 4, 5, 6, 7}

Set A after removing all elements

set()

**discard**()

**Code:**

## Python Code

```
A = {1, 2, 3, 4, 5, 6, 7}
# removing element 40 from A using discard,as 40 is not present in set A, discard does nothing and not raises error.
print("Set A before removing element 40 ")
print(A)
A.discard(40)
print("Set A after removing element 40 using discard")
print(A)
# removing 7 from set A
print("Set A before removing element 7")
print(A)
A.discard(7)
print("Set A after removing element 7 using discard")
print(A)
```

**Output:**

Set A before removing element 40

{1, 2, 3, 4, 5, 6, 7}

Set A after removing element 40 using discard

{1, 2, 3, 4, 5, 6, 7}

Set A before removing element 7

{1, 2, 3, 4, 5, 6, 7}

Set A after removing element 7 using discard

{1, 2, 3, 4, 5, 6}

**remove**()

**Code:**

## Python Code

```
A = {1, 2, 3, 4, 5, 6, 7}
# removing 7 from set A
print("Set A before removing element 7")
print(A)
A.remove(7)
print("Set A after removing element 7 using remove")
print(A)
# removing element 40 from A using remove,as 40 is not present in set A, remove raises a KeyError
print("Set A before removing element 40 ")
print(A)
A.remove(40)
print("Set A after removing element 40 using remove")
print(A)
```

**Output:**

Set A before removing element 7

{1, 2, 3, 4, 5, 6, 7}

Set A after removing element 7 using remove

{1, 2, 3, 4, 5, 6}

Set A before removing element 40

{1, 2, 3, 4, 5, 6}

Traceback (most recent call last):

File “c:\Users\angaj\Desktop\tuf codes\python_data_types.py”, line 11, in <module>

A.remove(40)

KeyError: 40

**isdisjoint(), issuperset(), issubset()**

**Code:**

## Python Code

```
A = {1, 2, 3, 4, 5, 6, 7}
B = {3, 4, 5, 6}
if A.isdisjoint(B):
print("Sets A and B are disjoint")
else:
print("Sets A and B are not disjoint")
if B.issubset(A):
print("set B is subset of set A")
else:
print("set B is not a subset of set A")
if A.issuperset(B):
print("set A is superset of set B")
else:
print("set A is not superset of set B")
```

**output:**

Sets A and B are not disjoint

set B is subset of set A

set A is superset of set B

### pop()

**Code:**

## Python Code

```
A = {1, 2, 3, 4, 5, 6, 7}
print("Set A before using pop method")
print(A)
print("Set A after calling pop method ")
A.pop()
print(A)
A.clear()
# Set A is empty now, calling pop will raise KeyError
A.pop()
```

**Output:**

Set A before using pop method

{1, 2, 3, 4, 5, 6, 7}

Set A after calling pop method

{2, 3, 4, 5, 6, 7}

Traceback (most recent call last):

File “c:\Users\angaj\Desktop\tuf codes\python_data_types.py”, line 9, in <module>

A.pop()

KeyError: ‘pop from an empty set’

**Built-in functions like all(), any(), enumerate() ,len() , max(),min(), sorted(), sum() can also be used with set two perform different tasks.**

Special thanks toplease check out this articleSaiSri Angajalafor contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam,