Python: Sets

Set is an unordered collection of items. Each element in the set must be unique. Sets remove the duplicate elements. Sets are mutable which means we can modify it after its creation.

The order of elements in a set is undefined though it may consist of various elements. It can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.

Creating a set

A set can be created in two ways:

By using curly braces:

It  is created by placing all the items (elements) inside curly braces {}, separated by comma.

set_1 = {'a','b','c','d'}

Output: {'c', 'd', 'a', 'b'}

Note: Insertion order is not maintained.

By using set() method

set() method is an in-built function.

set_1 = set({'a','b','c','d'})


{'a', 'c', 'd', 'b'}
<class 'set'>