Python - set() Function
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. |
Return Value
Returns a set containing all unique elements of passed iterable.
Example:
In the below example, set() function is used to create set using a given iterable.
#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 string as an iterable MySet = set('string') print(MySet) #using range() as an 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 Set Methods