
Python Set: How to create an empty set and declare a set
A Python set is a set of items written with curly braces.
s = {'a', 'b'}
Empty set
Both set and dictionary use curly braces and only curly braces represent a dictionary with no element.
s = {}
print(type(s)) # <class 'dict'>
An empty set is declared by set()
, a Python built-in function, as follows.
s = set()
print(s) # set()
print(type(s)) # <class 'set'>
How to use set()
s = set(3)
# TypeError: 'int' object is not iterable
It can't take values, but iterables (set, list, tuple, etc).
s1 = set({1, 2, 3})
s2 = set([4, 5, 6, 6])
s3 = set((7, 7, 7))
print(s1) # {1, 2, 3}
print(s2) # {4, 5, 6}
print(s3) # {7}
Comments
Powered by Markdown