Sets: Examples

 

Sets are a collections of unique items. Almost everything you can do with a set has an example below. Before we go too far, a picture is worth a thousand words, so…   for traditional sets –>

Unfortunately, not all PYTHON object set concepts can be easily visualized. Two types require a short explanation or a note – union and difference. Python sets can only contain unique items so if the two segments of difference contain identical members, only one will end up in a new “difference set”. Python unions are similar, the “base” set keeps all its members and only adds all the members from the new set that it does not already have.

The design for this example is for the user to download, run, and print out the result so that the code and the results can be compared side-by-side.

#SETS - unique (no duplicate items) unordered mutable collection
#create sets using the set constructor
print("Create 4 different sets to start:")
setA={'A1','A2','A3','B1','B2','B3'}
tempList=['B1','B2','B3']
setB=set(tempList)
setC=set(['C1','C2','C3','A1'])
print('Here are our first 3 sets.')
print(setA,'\n',setB,'\n',setC)
print("Make another set from this phrase:")
bstring = "Bannanas are nice"
print(bstring)
print("That set becomes: ")
setD=set(bstring)
print(setD)      
print("Note each letter is an item and duplicates are eliminated.")
#add an item
print("Add a letter 'J' to the set and it becomes...")
setD.add('J')
print(setD)
#copy set
print("Copy the set.")
setE=setD.copy()
print("The new setE is: ",setE)
#clear a set
print("Clear setD....poof")
setD.clear()
print("setD is now ",setD)
#delete a set
print("Completely delete setD....ZAP!")
del setD
try:
    print(setD)
except:
    print("Tried to access setD but it is gone- error resulted.")
#number of items in a set
print("The number of elements in SetE is: ",len(setE))
#remove an item
print("Let's get rid of that capital B with a remove command.")
setE.remove("B")
print("gone...Would have caused and error if 'B' was not in the set.")
print("Now we have ",setE)
print("If 'X' or 'n' are in the set lets get them out with discard.")
setE.discard('X')
setE.discard('n')
print("That gives us: ",setE)
print("'n' is gone and no error as a result of not finding 'X'.")
#find membership
print("Can confirm membership - look for 's' and 'n' in our set: ")
print("Do we have an 's'? ",('s' in setE))
print("Do we have an 'n'? ",('n' in setE))
print("Is 'A1' in setC? ",('A1' in setC))
print("Now for the part that makes sets a vauable tool:")
print("difference, intersection, isdisjoint, issubset, issuperset")
print("Just as a reminder: ")
print("setA: ",setA)
print("setB: ",setB)
print("setC: ",setC)
#difference
print("Difference of setA and setC: ",setA.difference(setC))
#intersection
print("Intersection of setA and setC: ",setA.intersection(setC))
#disjoint
print("Is disjoint setB and setC? ", setB.isdisjoint(setC))
#subset
print("Is setB a subset of setA? ",setB.issubset(setA))
#superset
print("Does setA contain setB? ",setA.issuperset(setB))
#union
print("Make a new setF with union of setA and setC.")
setF=set() # create an empty set with set constructor just for demo
setF=setA.union(setC)
print("setF is now: ",setF)
print("Note element 'A1' was not duplicated.")
#remove
print("Lets use remove to get rid of 'A1' from setC.....BOOM")
setC.remove('A1')
print("New setC is ",setC)
#pop
print("Remove and return an arbitrary element from setC.")
eleremoved=setC.pop()
print("The element Python removed was: ",eleremoved)
print("...and setC is now: ",setC)
#update
print("Use update to merge setA with setB after adding some new")
setA.add('C1')
setA.add('B1')
setB.update(setA)
print("New setB has no duplicates: ",setB)
#iteration
print("Iterate little setC")
Citer=iter(setC)
for i in range(2):
    print(next(Citer))