A set is a collection of elements which are unique. A set is created by using built-in set( ) function or by using curly braces which has elements separated by ‘comma’.
The following program shows a sets which are created by using curly braces and set( ) function .
setItems = {"pen", "pencil", "eraser"}
print(setItems)
# Using set() function
setItems = set(("pen", "pencil", "eraser"))
print(setItems)
A set item cannot be accessed by referring to its index number since they are unordered. Items in a set can be printed by using a for loop.
setItems = {"pen", "pencil", "eraser"}
for x in setItems:
print(x)
Output:
pencil
eraser
pen
An item can be added in a set by using the add( ) method. Multiple items and items of lists, strings, tuples and other sets can be added by using the update( ) method.
The following program shows add( ) and update( ) method which is applied to set.
An item in a set can be removed by using the remove( ) method or discard( ) method. remove( ) method only removes when that item is present otherwise it throws an error while discard( ) method does not throws that error.
An item can also be removed by using the pop( ) method. This method removes the last item but since the items are unordered in set, any of the items will be deleted. All the items of a set can be removed by using the clear( ) method.
# Use of remove() method
setItems = {"pen", "pencil", "eraser"}
setItems.remove("pencil")
print("After removing \"pencil\" set items are", setItems)
# Use of discard() method
setItems = {"pen", "pencil", "eraser"}
setItems.discard("eraser")
print(setItems)
# Use of pop() method
setItems = {"pen", "pencil", "eraser"}
removedItem = setItems.pop()
print(setItems)
print("Removed item is", removedItem)
# Use of clear() method
setItems = {"pen", "pencil", "eraser"}
setItems.clear()
print(setItems)
Output:
After removing "pencil" set items are {'pen', 'eraser'}
{'pencil', 'pen'}
{'pen', 'eraser'}
Removed item is pencil
set()
The elements of sets can be added together to form a new set using union( ) method or by using ‘|’ operator. Also the new set does not contain the duplicate items. The following program shows union( ) method and ‘|’ operator to have the elements in a new set( ).
Items which are common in sets can be found by using the intersection( ) method or by ‘&’ operator. The following program shows the use of intersection( ) method and ‘&’ operator to print the elements which are common in two sets( ).
Difference of set can be printed by using difference( ) method or by using ‘-‘ operator. Difference of set A and set B, which is (A – B) are the elements which are only present in set A. The following program shows the use of difference( ) method and ‘‘-‘ operator on two sets.
Frozen sets are immutable, that the elements cannot be changed once it is assigned. A frozen set is made by using the frozenset( ) method. The following program shows a frozen set.