The most common operations of Python set collections are adding and removing elements to the collection, and performing operations such as intersection, union, and difference between collections. This section will explain the specific implementation of these operations one by one.
To add elements to a set, you can use the add () method provided by the set type. The syntax of the method is:
setname.add (element)
Where:
It should be noted that the elements added using the add method can only be numbers, strings, tuples or boolean (True and False) values. You cannot add variable data such as lists, dictionaries, and collections, otherwise Python interpreter will report a TypeError. Example:
a = {9,8,7} a.add ((6,5)) print(a) a.add([1,2]) print (a)
The output is:
{8, 9, (6, 5), 7}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
[ipython-input-130-dd957b2ad825] in [module]
2 a.add ((6,5))
3 print(a)
----> 4 a.add([1,2])
5 print (a)
TypeError: unhashable type: 'list'
To remove a specified element from an existing set, you can use the remove method, which has the following syntax:
setname.remove (element)
Use this method to delete elements in the collection. It should be noted that if the deleted element is not included in the collection, this method will throw a KeyError. For example:
a = {9,8,7} a.remove (9) print (a) a.remove (9) print (a)
The output is:
{8, 7}
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
[ipython-input-131-0a47e504b8dc] in [module]
2 a.remove (9)
3 print (a)
----> 4 a.remove (9)
5 print (a)
KeyError: 9
In the above program, because element 9 in the collection has been deleted, when trying to delete again using the remove method, a KeyError will be raised.
If we don't want the interpreter to prompt KeyError when the deletion fails, we can also use the discard method. This method is exactly the same as the remove method. The only difference is that when deleting elements in the collection fails, this method will not throws errors.
Example:
a = {9,8,7} a.remove (9) print (a) a.discard (9) print (a)
The output is:
{8, 7}
{8, 7}
The most common operation of a set is to perform the operations of intersection, union, difference, and symmetric difference. First of all, it is necessary to popularize the meaning of each operation.
Arithmetic Operation | Python Operator | Meaning |
---|---|---|
Intersection | & | Take common elements of two sets |
Union | | | Take all elements of two sets |
Difference | - | Take elements from one set that are not in another set |
Symmetric Difference | ^ | Take elements in sets A and B that are not part of A & B |
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises