Professional Documents
Culture Documents
6 Sets
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
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
In [4]:
# To add more than item we have to use Udpate()
s.update([17,18])
In [5]:
s
In [6]:
# length of set
len(s)
Out[6]: 7
In [7]:
# To Remove the item
s.remove(12)
In [8]:
s
In [9]:
s.discard(13)
In [10]:
s
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
---------------------------------------------------------------------------
<ipython-input-2-5536cdf43f08> in <module>
----> 1 s4 = s1 + s2
In [29]:
s3 = s1.union(s2)
In [30]:
s3
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
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 [ ]: