Python - set() Function


Advertisements

The 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.

Example: Create set using an iterable

In the below example, set() function is used to create a set called MySet using an iterable like a list, tuple, set, etc.

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

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

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

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

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

Output

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

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

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

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

{1, 2, 3, 4, 5}

Example: Create set using dictionary as an iterable

In the below example, set() function is used to create a set called MySet using a dictionary as an iterable.

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

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

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

Output

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

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

{'London', 25, 'John'}

Example: set function applied on iterable containing dublicate elements

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

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

Output

{1, 2, 3, 4, 5}

Sets Methods




Advertisements