LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.
Lesson 25: Sets In Python
Sets In Python 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*, and unindexed. Set items are unchangeable,
but you can remove items and add new items.
Sets are written with curly brackets.
Example: How to Create a Set?
thisset = {"apple", "banana", "cherry"}
print(thisset)
the output will be
{'banana', 'cherry', 'apple'}
Note: the set list is unordered, meaning: the items will appear in a random order.
Sets are unordered, so you cannot be sure in which order the items will appear.
Set Items: Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered: Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
Unchangeable: Set items are unchangeable, meaning that we cannot change the items after the set has been created.
Once a set is created, you cannot change its items, but you can remove items and add new items.
Duplicates Not Allowed: Sets cannot have two items with the same value.
Example: Note that the Duplicate values will be ignored.
thisset = {"apple", "pineapple", "banana", "cherry", "apple"}
print(thisset)
output will be
{'cherry', 'banana', 'apple', 'pineapple'}
Get the Length of a Set: To determine how many items a set has, use the len() method.
Example: How to Get the number of items in a set?
thisset = {"apple", "pineapple", "banana", "cherry"}
print(len(thisset))
output will be
4
Set Items-Data Types String, int and boolean data types.
Example
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
print(set1)
print(set2)
print(set3)
output will be
{'cherry', 'apple', 'banana'}
{1, 3, 5, 7, 9}
{False, True}
A set can contain different data types like A set with strings, integers and boolean values.
Example
set1 = {"abc", 34, True, 40, "male"}
print(set1)
output will be
myset = {"orange", "banana", "cherry"}
output will be
thisset = set(("apple", "banana", "cherry"))
output will be
Orange
cherry
banana
apple
Example 2: Check if an "Item" is present in the set.
thisset = {"apple", "banana", "cherry"}
output will be
thisset = {"apple", "banana", "cherry"}
output
Add Sets
To add items from another set into the current set, use the update() method.
setA = {"apple", "banana", "cherry"}
output will be.
Add Any Iterable
The object in the update() method does not have to be a set, it can be any iterable object .
thisset = {"apple", "banana", "cherry", "pineapple"}
output will be.
Remove Item: How to Remove Set Items
1. Remove an item in a set, using the remove() method.
thisset = {"apple", "banana", "cherry"}
output will be.
2. Remove an item in a set, using the discard() method.
thisset = {"apple", "banana", "cherry"}
output will be.
3. Remove an item in a set, using the pop() method.
thisset = {"apple", "banana", "cherry"}
output will be
The clear() method: How to clear a set.
thisset = {"apple", "banana", "cherry"}
output will be
How to delete the Set?
thisset = {"apple", "banana", "cherry"}
Note: This will raise an error because the set no longer exists.(NameError: name 'thisset' is not defined)
Loop Sets: Loop Items, How to Loop throught a set?
Join Sets; How to Join Two Or More Sets In Python?
1. The union() method returns a new set with all items from both sets.
set1 = {"a", "b" , "c"}
output will be.
Note: This may differ every time you run the code as sets are unordered and unindex.
2. The update() method inserts the items in set2 into set1.
set1 = {"a", "b" , "c"}
output will be.
Note: This may differ every time you run the code as sets are unordered and unindex.
Both union() and update() will exclude any duplicate items.
Keep ONLY the Duplicates:
Example1: Keep the items that exist in both set x, and set y.
x = {"apple", "banana", "cherry"}
output wii be.
Example2: Return a set that contains the items that exist in both set x, and set y.
x = {"orange", "banana", "cherry"}
output will be.
Keep All, But NOT the Duplicates: Keep the items that are not present in both sets.
Example A
x = {"apple", "banana", "cherry"}
output will be.
Example B: Return a set that contains all items from both sets, except items that are present in both.
x = {"apple", "banana", "cherry", "orange"}
output will be
{True, 34, 40, 'male', 'abc'}
type() What is the data type of a set?
From Python's perspective, sets are defined as objects with the data type 'set'
Example
print(type(myset))
<class 'set'>The set() Constructor: How to create a set?
It is also possible to use the set() constructor to make a set. Using the set() constructor to make a set.
Example
# note the double round-brackets
print(thisset)
{'banana', 'apple', 'cherry'}
Note: the set list is unordered, so the result will display the items in a random order.Access Set Items; How to Access Items In A Set
You cannot access items in a set by referring to an index or a key. But you can loop through
the set items using a for loop, or ask if a specified value is present in a set, by using the
in keyword.
Example 1: Loop through the set, and print the values
the output will be
print("banana" in thisset)
TrueChange Items: How to Change Items In A Set?
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add() method.
Example A
thisset.add("orange")
print(thisset)
{'cherry', 'apple', 'banana', 'orange'}
Example
setB = {"pineapple", "mango", "papaya"}
setA.update(setB)
print(setA)
{'mango', 'apple', 'papaya', 'cherry', 'banana', 'pineapple'}
(tuples, lists, dictionaries etc.).
Example: Add elements of a list to at set
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
{'apple', 'cherry', 'banana', 'kiwi', 'pineapple', 'orange'}
Example
thisset.remove("cherry")
print(thisset)
{'apple', 'banana'}
Note: If the item to remove does not exist, remove() will raise an error.
Example
thisset.discard("apple")
print(thisset)
{'banana', 'cherry'}
Note: If the item to remove does not exist, discard() will NOT raise an error.
Example
x = thisset.pop()
print(x)
print(thisset)
the last item will be removed.
Note: Sets are unordered, so when using the pop() method, you do not know which item that gets removed.
In the example above when you run the code each time a different item may get removed. i.e.
print(x) #removed item(May differ eah time)
print(thisset) #the set after removal(May differ eah time).
Note: the set list is unordered, meaning: the items will appear in a random order.
Sets are unordered, so you cannot be sure in which order the items will appear.
This means which item gets removed & How the set will print after removal will depend on that partiular instance whih will be at radom.
The clear() method empties the set.
Example
thisset.clear()
print(thisset)
set()
The del keyword will delete the set completely.
Example
del thisset
print(thisset)
You can loop through the set items by using a for loop. Loop through the set, and print the values.
Example
output will be.
cherry
apple
banana
Note: Duplicate will be ignored.
There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set containing all items from both sets, or
the update() method that inserts all the items from one set into another.
Example
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
{'a', 2, 'c', 3, 'b', 1}
Example
set2 = {1, 2, 3, 4}
set1.update(set2)
print(set1)
{'b', 1, 2, 3, 4, 'c', 'a'}
The intersection_update() method will keep only the items that are present in both sets.
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)
{'apple'}
The intersection() method will return a new set, that only contains the items that are present
in both sets.
y = {"google", "microsoft", "orange"}
z = x.intersection(y)
print(z)
{'orange'}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)
{'google', 'banana', 'microsoft', 'cherry'}
Note: The symmetric_difference() method will return a new set, that contains only the elements that are NOT present in both sets.
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
{'banana', 'google', 'cherry', 'orange', 'microsoft'}