Python Tutorial Python Advanced Python References Python Libraries

Python - set() Function



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

Syntax

set(iterable)

Parameters

iterable Required. iterable like list, tuple, set, string , dictionary, etc.

Return Value

Returns a set containing all unique elements of passed iterable.

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', 'JAN', 'MAR'}
{'APR', 'FEB', 'JAN', 'MAR'}
{'t', 'r', 'g', 'n', 's', 'i'}
{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:

{'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 Set Methods