A set in python is the same concept of the set in Discret Math. A set contains unique unorder elements.
In python, a set is definded by putting “{}”
In [2]:
s = {1,2,3}
s
Out[2]:
In [5]:
s = {"1231",(1,2,3),2} # A set can contain different data type
A set is nonordered, so it can not access by indexing
In [7]:
s[0]
However, it can be access by iterating
In [6]:
for ele in s:
print ele
If feeding a set with same elements, it will only save that element once, for example,
In [12]:
s_1 = {1,1,(1,2),(1,2)}
s_1
Out[12]:
You can turn other data strcture in python into a set by using set() function
In [15]:
l = [1,2,3,3,2]
t = (2,2,2,1)
set(l)
Out[15]:
In [16]:
set(t)
Out[16]: