Definition: is a datatype that is unordered; mutable; no duplicate elements; but it is iterabel.

Python’s set class represents the mathematical notion of a set. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table. Since sets are unordered, we cannot access items using indexes like we do in lists.

Example 1: Create sets from string, tuple, list, and range

# empty set print(set())

# from string print(set('Python'))

 

# from tuple print(set(('a', 'e', 'i', 'o', 'u')))

 

# from list print(set(['a', 'e', 'i', 'o', 'u']))

 

# from range print(set(range(5)))

Output

 

set()

{'P', 'o', 't', 'n', 'y', 'h'}

 

{'a', 'o', 'e', 'u', 'i'}

 

{'a', 'o', 'e', 'u', 'i'}

 

{0, 1, 2, 3, 4}

Note: We cannot create empty sets using { } syntax as it creates an empty dictionary. To create an empty set, we use set().

Example 2: Create sets from another set, dictionary and frozen set

# from set print(set({'a', 'e', 'i', 'o', 'u'}))

 

# from dictionary print(set({'a':1, 'e': 2, 'i':3, 'o':4, 'u':5}))

 

# from frozen set frozen_set = frozenset(('a', 'e', 'i', 'o', 'u')) print(set(frozen_set))

Output

{'a', 'o', 'i', 'e', 'u'}

 

{'a', 'o', 'i', 'e', 'u'}

 

{'a', 'o', 'e', 'u', 'i'}