Python Set
Set
A Set is an unordered and unindexed collection of elements written within curly brackets. Sets are iterable and mutable. A set can never have duplicate values. The repetition of items is not allowed in a set.
s={'j',452,'apple',True,9.7,120,False,'green','green'}
We can also use the pop() method to remove an item from the set randomly. The clear() method is used to clear the entire set. To delete the complete set del keyword can be used.
A set can be iterated using the for-statement,
print('1.====================================') s={'j',452,'apple',True,9.7,120,False,'green','green'} for item in s: print(item) Output: 1.==================================== False True green 452 9.7 apple j 120
Adding items
A set can be updated with a single member(add() method) or multiple elements together(update() method).
s={'j',452,'apple',True,9.7,120,False,'green','green'} s.add(78) # ADD member s.update([96,'red',4.12]) #update set print(s) Output: {False, True, 'j', 96, 452, 4.12, 'green', 9.7, 'red', 78, 'apple', 120}
Removing members
The items of a set can be removed using remove() or discard() methods. The difference between them is that later will not raise an exception if the item does not exist in the set.
The pop() method removes the last item of the set but.as a set is unordered you will not be able to predict which element will be removed.
s={'j',452,'apple',True,9.7,120,False,'green','green'} s.remove(True) s.discard(9.7) print(s) #pop() method removes last item only. print('After popping last item') s.pop() print(s) Output: {'apple', False, 452, 'j', 'green', 120} After popping last item {False, 452, 'j', 'green', 120}
Clear the Set
The clear() method is used to clear a set.
s1={'my','test', 'set'} s1.clear() print(s1) Output: set()
Deleting a Set
The del command can be used to delete an entire set,
s1={'my','test', 'set'} del s1 # DELETE Set completely #print(s1) #will raise an errror as s1 is already deleted completely print('s1 deleted') Output: s1 deleted
Operations on Sets
We can use methods like intersection(), union(), difference(), symmetric_difference() and methods like isdisjoint(),issubset, issuperset() etc. to perform set operations in Python.