Sets in Python
A set is a mutable data type designed to store only unique values. A set looks like a list, except that its elements are enclosed in curly braces. The syntax for a set is:
st = {element1, element2, element3...}
To create a set, you must use the set
function. If you do not pass anything to its parameters, an empty set will be created:
st = set()
print(st) # set()
If you try to assign curly brackets to the variable st
, you will not create a set, but an empty dictionary:
st = {}
print(st) # {}
print(type(st)) # <class 'dict'>
To create a set filled with elements, you need to specify them in the parameter of the set
function. A set can be made from a string, an array, and a tuple:
st1 = set('abc')
st2 = set(['1', '2', '3'])
st3 = set((1, 2, 3))
print(st1) # {'a', 'c', 'b'}
print(st2) # {'1', '3', '2'}
print(st3) # {1, 2, 3}
The following code is given:
tst = {}
print(type(tst))
Tell me what will be output to the console.
The following code is given:
tst = set()
print(type(tst))
Tell me what will be output to the console.
The following code is given:
tst = {'x', 'y', 'z'}
print(type(tst))
Tell me what will be output to the console.
The following code is given:
tst = {'a': 1, 'b': 2, 'c': 3}
print(type(tst))
Tell me what will be output to the console.