Tutorial Study Image

Python set()

The built-in function set() is used to create sets in python. The set is a single variable that stores multiple data it should be unordered and unindexed, and cannot allow duplicate values.


set(iterable) #where iterable can be string,tuple,set,dictionary,etc
 

set() Parameters:

It takes a single parameter.Using { } we cannot create empty sets it creates an empty dictionary so we use set() to create an empty set.

Parameter Description Required / Optional
iterable  a sequence (string, tuple, etc.) or collection (set, dictionary, etc.) or an iterator object to be converted into a set Optional

set() Return Value

We cannot modify sets after their creation.

Input Return Value
no parameters  an empty set
iterable parameter a set constructed from the given iterable

Examples of set() method in Python

Example 1: How to 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}

Example 2: How to 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'}

Example 3: How to create set() for a custom iterable object


class PrintNumberlist:
    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

# print_num is an iterable
print_number = PrintNumberlist(5)

# creating a set
print(set(print_number))
 

Output:

{1, 2, 3, 4, 5}