Course Code: CSE 0613 2203B
Course Title: Introduction to Programming with
Python
Md. Shymon Islam
Lecturer
Department of Computer Science and Engineering
Shahjalal University of Science and Technology, Sylhet
Python Sets
• Sets are used to store multiple items in a single variable.
• Set is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Tuple, and Dictionary, all with different
qualities and usage.
• A set is a collection which is unordered, unchangeable, unindexed
and duplicates not allowed.
Python Sets
Sets are written with curly brackets.
Sets Example
True and 1 are same in set.
False and 0 are same in set.
Access Set Items
Use any loop to access each elements.
Add Set Items
To add one item to a set use the add() method.
Merge Two Sets
To merge two sets to a set use the update() method.
Merge Sets with Other Collection (Arrays)
The object in the update() method does not have to be a set, it can be
any iterable object (tuples, lists, dictionaries etc.).
Remove Set Items
To remove an item in a set, use the remove() method or discard()
method.
Join Sets
There are several ways to join two or more sets in Python.
• The union() and update() methods joins all items from both sets.
• The intersection() method keeps ONLY the duplicates.
• The difference() method keeps the items from the first set that are not
in the other set(s).
• The symmetric_difference() method keeps all items EXCEPT the
duplicates.
Union Method
The union() method returns a new set with all items from both sets.
Union (Join Multiple Sets)
Join a Set and a Tuple
Intersection Method
The intersection() method will return a new set, that only contains the
items that are present in both sets.
Symmetric Difference Method
The symmetric_difference() method will will keep only the elements
that are NOT present in both sets.