Python Basic Data Structure — Set




Set







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]:
{1, 2, 3}
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]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-4e98c4f87897> in <module>()
----> 1 s[0]

TypeError: 'set' object does not support indexing

However, it can be access by iterating

In [6]:
for ele in s:
    print ele
2
1231
(1, 2, 3)

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]:
{1, (1, 2)}

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]:
{1, 2, 3}
In [16]:
set(t)
Out[16]:
{1, 2}