Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

12/30/21, 12:07 PM 6 Sets

SETS
A set is a collection which is unordered and unindexed. In Python sets are written with curly
brackets.

In [1]:
s ={12,13,14,15}

In [2]:
s

Out[2]: {12, 13, 14, 15}

In [3]:
# In Set we cannnot access by an index number but we can use them using for Loop

In [4]:
s ={12,13,14,15}

for x in s:

print(x)

12

13

14

15

In [5]:
# To change the items : add()

In [2]:
s.add(16)

In [3]:
s

Out[3]: {12, 13, 14, 15, 16}

In [4]:
# To add more than item we have to use Udpate()

s.update([17,18])

In [5]:
s

Out[5]: {12, 13, 14, 15, 16, 17, 18}

In [6]:
# length of set

len(s)

Out[6]: 7

file:///C:/Users/rgandyala/Downloads/6 Sets.html 1/3


12/30/21, 12:07 PM 6 Sets

In [7]:
# To Remove the item

s.remove(12)

In [8]:
s

Out[8]: {13, 14, 15, 16, 17, 18}

In [9]:
s.discard(13)

In [10]:
s

Out[10]: {14, 15, 16, 17, 18}

In [11]:
s ={12,13,14,15}

In [26]:
s.clear()

In [27]:
s

Out[27]: set()

In [1]:
# To add two sets

s1 ={12,13,14,15}

s2={16,17,18}

In [2]:
s4 = s1 + s2

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

<ipython-input-2-5536cdf43f08> in <module>

----> 1 s4 = s1 + s2

TypeError: unsupported operand type(s) for +: 'set' and 'set'

In [29]:
s3 = s1.union(s2)

In [30]:
s3

Out[30]: {12, 13, 14, 15, 16, 17, 18}

In [33]:
s ={12,13,14,15}

In [34]:
file:///C:/Users/rgandyala/Downloads/6 Sets.html 2/3
12/30/21, 12:07 PM 6 Sets

s.discard(14)

In [35]:
s

Out[35]: {12, 13, 15}

In [13]:
# Set doesn't allow duplicates. They store only one instance.

s = {1, 2, 3, 1, 4}
s

Out[13]: {1, 2, 3, 4}

In [37]:
# Add multiple elements

s.update([5, 6, 1])

Out[37]: {1, 2, 3, 4, 5, 6}

In [ ]:

file:///C:/Users/rgandyala/Downloads/6 Sets.html 3/3

You might also like