Python set()

The set() constructor constructs a Python set from the given iterable and returns it.

The syntax of set() constructor is:

set([iterable])

Recommended Reading: Python sets and how to use them?


set() Parameters

set() takes a single optional parameter:

  • iterable (Optional) - a sequence (string, tuple, etc.) or collection (set, dictionary, etc.) or an iterator object to be converted into a set

Return value from set()

set() returns:

  • an empty set if no parameters are passed
  • a set constructed from the given iterable parameter

Example 1: How set() works for a sequence: string, tuple, list, 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)))

When you run the program, the output will be:

set()
{'P', 'o', 't', 'n', 'y', 'h'}
{'a', 'o', 'e', 'u', 'i'}
{'a', 'o', 'e', 'u', 'i'}
{0, 1, 2, 3, 4}

Note: Empty sets cannot be created using {}, use set()


Example 2: How set() works for a collection: set, dictionary and frozen set?

# for 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
frozenSet = frozenset(('a', 'e', 'i', 'o', 'u'))
print(set(frozenSet))

When you run the program, the output will be:

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

Note: Dictionary keys are used for set creation. And, ordering of the elements may not be the same.


Example 3: How set() works for custom iterable object?

class PrintNumber:
    def __init__(self, max):
        self.max = max

    def __iter__(self):
        self.num = 0
        return self

    def __next__(self):
        if(self.num >= self.max):
            raise StopIteration
        self.num += 1
        return self.num

printNum = PrintNumber(5)

# creating a set
print(set(printNum))

When you run the program, the output will be:

{1, 2, 3, 4, 5}