Python Tutorial Python Advanced Python References Python Libraries

Python set() Function



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, dictionary and range iterable.

Syntax

set(iterable)

Parameters

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

Example:

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

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

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

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

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

The output of the above code will be:

{'APR', 'FEB', 'MAR', 'JAN'}
{'APR', 'FEB', 'MAR', 'JAN'}
{'i', 'n', 't', 'g', 's', 'r'}
{1, 2, 3, 4, 5}

Example: using dictionary iterable

In the example below, 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:

{'city', 'name', 'age'}
{'city', 'name', 'age'}
{25, 'London', '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