لَآ إِلَـٰهَ إِلَّا هُوَ
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
{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

myset = {"orange", "banana", "cherry"}
print(type(myset))

output will be
<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

thisset = set(("apple", "banana", "cherry"))
# note the double round-brackets
print(thisset)

output will be
{'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

Orange

cherry

banana

apple

Example 2: Check if an "Item" is present in the set.

thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)

output will be
True

Change 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 = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)

output
{'cherry', 'apple', 'banana', 'orange'}

Add Sets To add items from another set into the current set, use the update() method.
Example

setA = {"apple", "banana", "cherry"}
setB = {"pineapple", "mango", "papaya"}
setA.update(setB)
print(setA)

output will be.
{'mango', 'apple', 'papaya', 'cherry', 'banana', 'pineapple'}

Add Any Iterable The object in the update() method does not have to be a set, it can be any iterable object .
(tuples, lists, dictionaries etc.).
Example: Add elements of a list to at set

thisset = {"apple", "banana", "cherry", "pineapple"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)

output will be.
{'apple', 'cherry', 'banana', 'kiwi', 'pineapple', 'orange'}

Remove Item: How to Remove Set Items

1. Remove an item in a set, using the remove() method.
Example

thisset = {"apple", "banana", "cherry"}
thisset.remove("cherry")
print(thisset)

output will be.
{'apple', 'banana'}
Note: If the item to remove does not exist, remove() will raise an error.

2. Remove an item in a set, using the discard() method.
Example

thisset = {"apple", "banana", "cherry"}
thisset.discard("apple")
print(thisset)

output will be.
{'banana', 'cherry'}
Note: If the item to remove does not exist, discard() will NOT raise an error.

3. Remove an item in a set, using the pop() method.
Example

thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)

output will be
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: How to clear a set.
The clear() method empties the set.
Example

thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)

output will be
set()

How to delete the Set?
The del keyword will delete the set completely.
Example

thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)

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?
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.

Join Sets; How to Join Two Or More Sets In Python?
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.

1. The union() method returns a new set with all items from both sets.
Example

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

output will be.
{'a', 2, 'c', 3, 'b', 1}

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.
Example

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3, 4}
set1.update(set2)
print(set1)

output will be.
{'b', 1, 2, 3, 4, 'c', 'a'}

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:
The intersection_update() method will keep only the items that are present in both sets.

Example1: Keep the items that exist in both set x, and set y.

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)

output wii be.
{'apple'}
The intersection() method will return a new set, that only contains the items that are present in both sets.

Example2: Return a set that contains the items that exist in both set x, and set y.

x = {"orange", "banana", "cherry"}
y = {"google", "microsoft", "orange"}
z = x.intersection(y)
print(z)

output will be.
{'orange'}

Keep All, But NOT the Duplicates: Keep the items that are not present in both sets.

Example A

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)

output will be.
{'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.

Example B: Return a set that contains all items from both sets, except items that are present in both.

x = {"apple", "banana", "cherry", "orange"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)

output will be
{'banana', 'google', 'cherry', 'orange', 'microsoft'}