Python Tutorial - Set Basic Operations

Python Exercise Lists

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.

Python Set Basic Operations - Add Elements

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:

  • setname represents the collection of elements to be added;
  • element represents the content of the elements to be added.

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'

Python Set Basic Operations - Remove Elements

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}

Python Set - Intersection, Union, and Difference Operations

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)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression


More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises