Trusted answers to developer questions

Muhammad Muzammil

A Python **set** is a collection of elements of any data type except mutable elements (such as lists, sets, dictionaries, etc.). However, no element can be repeated. The figure below shows examples of two sets, $A$ and $B$.

Python’s built-in data type ** set()** and its helper functions can be leveraged to make sets and perform different operations on them.

`union()`

`intersection()`

For intersection of $A$ and $B$, you can use the following syntax:

```
intersection_set = A.intersection(B)
```

For union:

```
union_set = A.union(B)
```

The **intersection** of two sets is the collection of elements that are present in both sets. In the example of sets $A$ and $B$, we can see that the element $2$ is common in both. Hence, the intersection of $A$ and $B$ will be $\{ 2 \}$.

The program below prints the intersection of $A$ and $B$.

def main (): set_A = set({1, 2, "hello"}) set_B = set({2, 3, 10}) set_intersection = set_A.intersection(set_B) print(set_intersection) main ()

The **union** of two sets is the set of all elements that are present in the two sets. In $A$ and $B$, the collection of all elements is $\{1, 2, 'hello', 3, 10\}$.

The Python program below shows how to find the union of two sets.

def main (): set_A = set({1, 2, "hello"}) set_B = set({2, 3, 10}) set_intersection = set_A.union(set_B) print(set_intersection) main ()

RELATED TAGS

python

communitycreator

CONTRIBUTOR

Muhammad Muzammil

RELATED COURSES

View all Courses

Keep Exploring

Related Courses