Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


The Python set() function (or set() constructor) is used to create set using iterable object. A iterable object can be any data structure like list, tuple, set, string and dictionary etc. The range() function can also be used as an iterable.

Syntax

set(iterable)

Parameters

iterable Required. iterable like list, tuple, set, string , dictionary and range() etc.

Example:

In the below example, set() function is used to create set using a given iterable.

#using list as iterable
MySet = set(['JAN', 'FEB', 'MAR', 'APR'])
print(MySet)

#using tuple as iterable
MySet = set(('JAN', 'FEB', 'MAR', 'APR'))
print(MySet)

#using string as iterable
MySet = set('string')
print(MySet)

#using range() as iterable
MySet = set(range(1,6))
print(MySet)

The output of the above code will be:

{'JAN', 'FEB', 'MAR', 'APR'}

{'JAN', 'FEB', 'MAR', 'APR'}

{'s', 't', 'r', 'i', 'n', 'g'}

{1, 2, 3, 4, 5}

Example: Using dictionary as iterable

In the below example, set() function is used to create set from a given dictionary.

MyDict = {
  'name': 'John',
  'age': 25,
  'city': 'London'
}
MySet = set(MyDict)
print(MySet)

MySet = set(MyDict.keys())
print(MySet)

MySet = set(MyDict.values())
print(MySet)

The output of the above code will be:

{'name', 'age', 'city'}

{'name', 'age', 'city'}

{'London', 25, 'John'}

Example: removing duplicate elements

In set, duplication of element is not allowed. Therefore, set() function removes any duplicate elements found in iterable.

MySet = set((1,2,2,3,4,5,5))
print(MySet)

The output of the above code will be:

{1, 2, 3, 4, 5}

❮ Python Built-in Functions