set() overview
Python set() function creates a set in Python. It is an alternative to creating a set by using curly brackets. To create an empty set we have to use the set() function because empty curly brackets create an empty dictionary and not an empty set.
create an empty set
To create an empty set, call the set() function without any argument.
It's not possible to create an empty set using curly brackets because it would create an empty dictionary instead of an empty set.
# create empty set
mySet = set()
print(mySet)
The empty set is created and printed. To verify the type of the returned object, use the type() function.
set()
create a set of range
To create a new set of a specific range, use the range() function combined with set().
# create new set of range
mySet = set(range(5))
print(mySet)
The set() function created a new set of five elements.
{0, 1, 2, 3, 4}
set() syntax
The syntax of the set() function is:
set([iterable])
create set of string
If we convert a string to a set, each character is converted to one element of the set.
# create a set of string
myString = 'Python'
mySet = set(myString)
print(mySet)
The set() function converts the string into a set. Each letter is one element of the set.
{'y', 't', 'h', 'P', 'o', 'n'}
create set of list
If we create a set of a list, remember that elements in sets are unique. This means that duplicates in the list will be omitted. The same rule applies to tuples.
# create set of list
myList = ['one', 'one', 'two', 'three']
mySet = set(myList)
print(mySet)
The element 'one' is twice in our list. If we convert it to a set, it will contain the element only once.
{'one', 'three', 'two'}
create set of nested tuple
If we convert a nested tuple to a set, it will contain all the elements of the tuple.
# create set of nested tuple
myTuple = ((3, 4), (5, 6))
mySet = set(myTuple)
print(mySet)
The nested tuple is converted into a set and returned.
{(5, 6), (3, 4)}
create set of dictionary
If we convert a dictionary to a set, only the keys are used. The values will be omitted.
# convert dictionary to set
myDict = {'one': 1, 'two': 2, 'three': 3}
mySet = set(myDict)
print(mySet)
The set() function converts the dictionary to a new set. The new set contains only the keys, not the values of the dictionary.
{'one', 'three', 'two'}
set() arguments
The set() function accepts one optional argument. If you pass an iterable like a string or tuple to the set() function, it will be used to convert it to a set. If no argument is passed an empty set will be created.
set() return values
The set() function returns a newly created set based on the given iterable or an empty set if no iterable is passed.