# Sets.pdf - Sets-> A set is an unordered collection of items...

• 8

This preview shows page 1 - 3 out of 8 pages.

Sets -> A set is an unordered collection of items. Every element is unique (no duplicates). -> The set itself is mutable. We can add or remove items from it. -> Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc. Set Creation In [1]: In [1]: In [2]: In [3]: set([1, 2, 3]) <type 'set'> {1, 2, 3, 4} {1, 2, 3} <class 'set'> #set of integers s = { 1 , 2 , 3 } print (s) #print type of s print ( type (s)) #set doesn't allow duplicates. They store only one instance. s = { 1 , 2 , 3 , 1 , 4 } print (s) #we can make set from a list s = set ([ 1 , 2 , 3 , 1 ]) print (s) #initialize a set with set() method s = set () print ( type (s)) Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
Add element to a Set In [4]: In [5]: In [6]: In [11]: Remove elements from a Set -------------------------------------------------------------------- ------- TypeError Traceback (most recent cal l last) <ipython-input-4-c52fc339e293> in <module> () 4 5 #set object doesn't support indexing ----> 6 print ( s [ 1 ]) #will get TypeError TypeError : 'set' object does not support indexing {1, 2, 3} {1, 2, 3, 5, 6} {1, 2, 3, 5, 6, 8, 9, 10} #we can add single element using add() method and #add multiple elements using update() method s = { 1 , 3 } #set object doesn't support indexing print (s[ 1 ]) #will get TypeError #add element s.add( 2 ) print (s) #add multiple elements s.update([ 5 , 6 , 1 ]) print (s)