Fundamental

HTML

JavaScript

Python

Fundamental of Computer

DBMS

Python: Set

 A Python set is the collection of unordered items. Each element in the set must be unique, immutable and the sets romove the duplicate elements. Sets are mutable which means we can modify it after its creation.

Unlike other collection in Python, there is no index attached to the elements of a set. Means we cannot directly access any element of a set by index. However, we can print them together or we can get the list of the elements by looping through the set.

Creating a Set:

The Sets are created by  immutable items, separated from each other by comma, enclosed by curly braces{}. Python also provides the set() method, which can be used to create the set by the passed sequence.

Example 1: Using curly braces

Days={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
print(Days)
print(type(Days))
print("Looping through the set elements...")
for i in Days:
    print(i)

Output:

{'Monday', 'Sunday', 'Thursday', 'Friday', 'Saturday', 'Tuesday', 'Wednesday', }
<class 'set'>
Monday
Sunday
Thursday
Friday
Saturday
Tuesday
Wednesday

Example 2: Using set() method

Days=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"])
print(Days)
print(type(Days))
print("Looping through the set elements...")
for i in Days:
    print(i)

Output:

{'Sunday', 'Monday', 'Saturday', 'Wednesday', 'Tuesday', 'Friday', 'Thursday'}
<class 'set'>
Sunday
Monday
Saturday
Wednesday
Tuesday
Friday
Thursday

It can contain any type of element such as integer, float, tuple etc. But mutable elements (list, dictionary, set) can't be a member of set. consider the following example:

#creating a set which have immutable elements
set1={1, 2, 3, "python", 6.76, 89}
print(type(set1))
#creating a set which have mutable elements
set2={1, 2, 3, ["python", 6]}
print(type(set2))

Output

<class 'set'>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'set2' is not defined. 

In the above code, we have created two sets, the set set1 have immutable elements and set2 have one mutable element as a list, while checking the type of set2, it raised an error, which means set can containonly immutable elements.
Creating an empty set is a slightly different because empty curly braces{} are also used to create a dictionary as well. So Python provides the set{} method used without an argument to create an empty set. 

#empty curly braces will create dictionary
set3={}
print(type(set3))
#empty set using set{} function
set4=set()
print(type(set4))

Output:

<class 'dict'>
<class 'set'>

Let's see what happens if we provide the duplicate element to the set.

set5={1, 2, 2, 3, 4, 4, 4, 5, 7, 7}
print("Return set with unique element", set5)

Output:

Return set with unique element {1, 2, 3, 4, 5, 7}

In above example, we can see that set5 consists of many duplicate values but when we printed it removed all the duplicates from the set.

Adding items to the set:
Python provides the add() method and update() method which can be used to add some particular item to the set. The add() method is used to add a single element whereas the update() method is used to add multiple elements to the set. Consider the following example:

Example 1: Using Add () Method

weeks=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"])
print("\nPrinting the original set...")
print(weeks)
print("\nAdding other days to the set...");
weeks.add("Friday");
weeks.add("Saturday");
print("\nPrinting the modified set...");
print(weeks)
print("\nLooping through the set elements...")
for i in weeks:
    print(i) 

Output:

{'Monday', 'Sunday', 'Wednesday', 'Thursday', 'Tuesday'}
Adding other days to the set...
Printing the modified set...
{'Saturday', 'Monday', 'Sunday', 'Wednesday', 'Thursday', 'Tuesday', 'Friday'}
Looping through the set elements...
Saturday
Monday
Sunday
Wednesday
Thursday
Tuesday
Friday

To add more than one item at a time in the set, Python provides the update() method. It accepts iterable as an argument.
Consider the following example:

Example 2: Using Update () Method

weeks=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"])
print("\nPrinting the original set...")
print(weeks)
print("\nUpdating the original set...");
weeks.update(["Friday", "Saturday"]);
print("\nPrinting the modified set...");
print(weeks)
print("\nLooping through the set elements...")
for i in weeks:
    print(i) 

Output:

{'Sunday', 'Thursday', 'Tuesday', 'Monday', 'Wednesday'}
Adding other days to the set...
Printing the modified set...
{'Sunday', 'Friday', 'Thursday', 'Tuesday', 'Monday', 'Wednesday', 'Saturday'}
Looping through the set elements...
Sunday
Friday
Thursday
Tuesday
Monday
Wednesday
Saturday

Removing items from the set:
Python provides the discard() method and remove () method which can be used to remove the items from the set. But there is a slight difference between both the methods discard()  method and remove() method, that if the item is not available in the list, then the set remain uneffected by discard() method but in the same condition , it shows an error message when we use remove() method.

Consider the following example:

Example 1: Using discard() method:

weeks=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"])
print("\nPrinting the original set...")
print(weeks)
print("\nRemovind some days from the set...");
weeks.discard("Monday");
weeks.discard("Wednesday");
print("\nPrinting the modified set...");
print(weeks)
print("\nLooping through the set elements...")
for i in weeks:
    print(i) 

Output:

{'Monday', 'Sunday', 'Wednesday', 'Thursday', 'Tuesday'}
Removing some days from the set...
Printing the modified set...
{'Sunday', 'Thursday', 'Tuesday'}
Looping through the set elements...
Sunday
Thursday
Tuesday

Example 2: Using remove() method:

weeks=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"])
print("\nPrinting the original set...")
print(weeks)
print("\nRemovind some days from the set...");
weeks.remove("Monday");
weeks.remove("Wednesday");
print("\nPrinting the modified set...");
print(weeks)
print("\nLooping through the set elements...")
for i in weeks:
    print(i) 

Output:

{'Monday', 'Sunday', 'Wednesday', 'Thursday', 'Tuesday'}
Removing some days from the set...
Printing the modified set...
{'Sunday', 'Thursday', 'Tuesday'}
Looping through the set elements...
Sunday
Thursday
Tuesday

pop() method:
We can also use the pop() method to remove the item. 
Consider the following example to remove the item from a set using pop() method:

weeks=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"])
print("\nPrinting the original set...")
print(weeks)
print("\nRemovind some days from the set...");
weeks.pop();
weeks.pop();
print("\nPrinting the modified set...");
print(weeks)

Output:

{'Monday', 'Wednesday', 'Thursday', 'Tuesday', 'Sunday'}
Removing some days from the set...
'Monday'
'Wednesday'
Printing the modified set...
{'Thursday', 'Tuesday','Sunday'}

clear() method:
Python provides the clear() method to remove all the items from the list.
Consider the following example to remove all the items from the list by using clear() method:

weeks=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"])
print("\nPrinting the original set...")
print(weeks)
print("\nRemovind all the  days from the set...");
weeks.clear()
print("\nPrinting the modified set...");
print(weeks)

Output:

{'Monday', 'Wednesday', 'Thursday', 'Tuesday', 'Sunday'}
Removing all the days from the set...

Printing the modified set...
set()

Join sets
There are several methods to join two or more sets in Python.
union() and update() methods: Joins all items from both sets.
intersection() method: Keeps only the duplicates.
differance() method: Keeps the items from the first set, which are not in other sets.
symmetric_difference() method: Keeps all items except the duplicates.

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

Example: Join set1 and set2 into a new set:

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

Output:

{'a', 1, 2, 3, 'b', 'c'}

We can use the | operator instead of union() method and we will get the same result.


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

Output:

{'a', 1, 2, 3, 'b', 'c'}

Join Multiple Sets:
All the joining methods and operators can be used to join multiple sets.
When using a method, just add more sets in the parentheses, separated by commas:

Example: Join multiple sets with the union() method:
set1={"a", "b", "c"}
set2={1, 2, 3}
set3={"apple","banana"}
set4={"swift", "desire"}
set5=set1.union(set2, set3, set4)
print(set5)

Output:

{1, 2, 3, 'desire', 'banana', 'apple', 'a', 'swift', 'b', 'c'}
 
When using the | operator, separate the sets with more | operator:

set1={"a", "b", "c"}
set2={1, 2, 3}
set3={"apple","banana"}
set4={"swift", "desire"}
set5=set1|set2|set3|set4
print(set5)

Output:

{'apple'1, 'c', 2, 3, 'desire', 'a', 'banana', 'swift', 'b'}

Join a Set and a Tuple:
union() method:
The union() method allows us to join a set with other data type like a list or tuple. The result will be a set.

Example to join a set with a tuple:

set_={"a", "b", "c"}
tuple_=(1, 2, 3)
set2_=set_.union(tuple_)
print(set2_)

Output:

{'b'1, 2, 3, 'a', 'c'}
With | operator we cannot join a set with other data types, as we can do with union() method.
 
update() method:
The update() method inserts all items from one set to another. It changes the original set and doesn't create a new one.

Example to merge one set into another set by update() method:
set1={"a", "b", "c"}
set2={1, 2, 3}
set1.update(set2)
print(set1)

Output:

{'b'1, 2, 3, 'a', 'c'}

The union() and update() methods both will exclude the duplicate items.

intersection() method:
It keeps only the duplicates. The intersection() method will return a new set, that only contains the items that are present in both sets

Example to join set1 and set2 but keep only the duplicates:

set1={"USA", "Canada", "Uganda", "Argentina"}
set2={"Uganda", "Chile", "Malaysia","Argentina"}
set3=set1.intersection(set2)
print(set3)

Output:

{'Uganda', 'Argentina'}

difference() method:
The difference() method will return a new set that will contain only the items from the first set that are not present in other set.

Example: Keep all items from set1 that are not in set2:
set1={"USA", "Canada", "Uganda", "Argentina"}
set2={"Uganda", "Chile", "Malaysia","Argentina"}
set3=set1.difference(set2)
print(set3)

Output:

{'USA', 'Canada'}

We can use the - operator instead of difference() method and we get the same result:

Example: Use - operator to join two sets:
set1={"USA", "Canada", "Uganda", "Argentina"}
set2={"Uganda", "Chile", "Malaysia","Argentina"}
set3=set1-set2
print(set3)

Output:

{'USA', 'Canada'}

Note: - operator only allows us to join one set to another set, but not applicable for other data types like we can do with difference() method.

The difference_update() method will also keep the items from the first set that are not in other set, but it changes the original set instead of making a new set.

Example: Keep all items from set1 that are not in set2 using difference_update() method.

set1={"USA", "Canada", "Uganda", "Argentina"}
set2={"Uganda", "Chile", "Malaysia","Argentina"}
set1.difference_update(set2)
print(set1)

Output:

{Canada', 'USA'}

Symmetric Differences:
The symmetric_difference() method will keep only the elements that are not present in both sets.

Example: Keep items that are not present in both sets:

set1={"USA", "Canada", "Uganda", "Argentina"}
set2={"Uganda", "Chile", "Malaysia","Argentina"}
set3=set1.symmetric_difference(set2)
print(set3)

Output:

{Canada', 'Malasia', 'USA', 'Chile'}

We can use ^ operator instead of symmetric_difference() method and we get the same result.

set1={"USA", "Canada", "Uganda", "Argentina"}
set2={"Uganda", "Chile", "Malaysia","Argentina"}
set3=set1^set2
print(set3)

Output:

{Canada', 'Malaysia', 'USA', 'Chile'}
Note: ^ operator only allows us to join one set to another set, but not applicable for other data types like we can do with symmetric_difference() method.

The symmetric_difference_update() method will also keep all except duplicates and it will change the original set instead of returning a new set.

Example: Keep the items that are not common in both sets using symmetric_difference() method.

set1={"USA", "Canada", "Uganda", "Argentina"}
set2={"Uganda", "Chile", "Malaysia","Argentina"}
set1.symmetric_difference_update(set2)
print(set1)

Output:

{'USA', 'Chile', Canada', 'Malaysia'}

Set Comparisons:
In Python, you can compare sets to check if they are equal, if one set is a subset or superset of another, or if two sets have elements in common.

Here are the set comparison operators available in Python:
  • = = checks if the two sets have same elements, regardless to their order.
  • != checks if two sets are not equal.
  • < checks if the left set is the proper subset of the right set.(i.e. All elements in the left set are also in the right set but there are also some additional elements in the right set).
  • <= checks if the left set is the subset of the right set.(i.e. All elements in the left set are also in the right set). 
  • > checks if the left set is the proper superset of the right set.(i.e. All elements in the right set are also in the left set but there are also some additional elements in the left set).
  • >= checks if the left set is the superset of the right set.(i.e. All elements in the right set are also in the left set). 
Consider the following example:

month1={"January", "February", "March", "April"}
month2={"January", "February"}
month3={"January", "February", "May"}
print(month1>month2)
print(month1<month2)
print(month2==month3)

Output:

True
False
False

In above example, in first case, month1 is superset of month2, so prints True. In second case month1 is not subset of month2, so prints false. In third case month2 and month3 are not equivalent so prints false.

FrozenSets:
In Python, frozen set is an immutable built-in set data type. It is similar to the set but its elements cannot be changed, once it created. Like a set, a frozen set is also an unordered collection of unique elements and also they can be used as the same way like a set except the difference is the elements cannot be changed after creation.
One of the advantage of using frozen set is that it is hashable. Hashable means it is used as the keys of the dictionary or as the element of other set. The hash value of a frozen set remains constant as contents of it cannot be changed. While a standard set in Python contains the elements which can be easily changed after its creation.
The frozen set also supports the same operations like union, intersection, difference, symmetric difference etc as supported by a standard set. Also supports the operations like min(), max() and len(), because these are the operations don't modify the elements.
Now in an example we create a frozen set:

fset=frozenset([1, 2, 3, 4, 5, 6, 7, 8, 9])
print(type(fset))
print("\nPrinting the contents of frozen set...")
for i in fset:
    print(i);

Output:

<class 'frozenset'>
1
2
3
4
5
6
7
8
9

Now we try to modify the frozenset. i.e We try to add an element.

fset=frozenset([1, 2, 3, 4, 5, 6, 7, 8, 9])
print(type(fset))
print("\nNow we are trying to add the content in frozen set...")
fset.add(10) # gives an error

Output:

<class 'frozenset'>
Now we are trying to add the content in frozen set...
AttributeError: 'frozenset' object has no attribute 'add'

FrozenSet for the dictionary:
If we take a dictionary as the element of a frozen set, it will take only the key element from the dictionary.
Understand it by following example:

Dictionary={"Name":"Abraham", "Country":"Jakarta", "EmpId":101}
print(type(Dictionary))
print(Dictionary)
fset=frozenset(Dictionary)
print(type(fset))
print("\nFrozenset will take only key element from dictionary...")
for i in fset:
    print(i)

Output:

<class 'dict'>
{'Name':'Abraham', 'Country':'Jakarta','EmpId':101}
<class 'frozenset'>
Frozenset will take only key element from dictionary...
EmpId
Name
Country

Some examples of Python Set:
Example1: Write a program to remove the given number from the set.

my_set={2, 4, 6, 8, 10, 12, 13, 14, 16, 18, 20}
n=int(input("Enter the number you want to remove - "))
my_set.discard(n)
print("After removing, my numbers are:", my_set)

Output:

Enter the number you want to remove - 13
After removing, my numbers are: 
{2, 4, 6, 8, 10, 12, 14, 16, 18, 20}

Note: If the above program will not run in your compiler as whole then run it in two parts
in first part run just above two lines, after that last two lines.

Example2: Write a program to add multiple elements to the set

my_set={"even","numbers", 2, 4, 6}
my_set.update(["odd", "numbers", 1, 3, 5,7])
print("separate even and odd numbers from the set", my_set)

Output:

separate even and odd numbers from the set{1, 2, 3, 4, 5, 6, 7, 'even', 'odd', 'numbers'}

Example3: Write a program to find the union between two sets

even_num={2, 4, 6, 8, 10}
odd_num={1, 3, 5, 7, 9}
natural_num=even_num.union(odd_num)
print(natural_num)

Output:

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Example4: Write  program to find intersection between two sets

prime_num={1, 2, 3, 5, 7}
odd_num={1, 3, 5, 7, 9}
common_num=prime_num.intersection(odd_num)
print(common_num)

Output:

{1, 3, 5, 7}

Example5: Write a program to find issubset, issuperset superset

month1={"January", "February", "March", "April"}
month2={"January", "February"}
month3={"January", "February", "May"}
issuperset=month1>=month2
print(issuperset)
issubset=month1<=month2
print(issubset)
issuperset=month3>=month2
print(issuperset)
issubset=month3<=month2
print(issubset)

Output:

True
False
True
False

Python built-in set methods:

SN

Method

Description

1

add item()

It adds an item to the set. It has no effect if the item is already present in the set.

2

clear()

It deletes all the items from the set.

3

copy()

It returns a copy of the set.

4

difference_update(….)

It modifies this set by removing all the items that are also present in the specified sets.

5

discard(item)

It removes the specified item from the set.

6

intersection()

It returns a new set that contains only the common elements of both or more than two sets.

7

intersection_update(….)

It removes the items from the original set that are not present in both or more than two sets.

8

isdisjoint(….)

Return True if two sets have a null intersection.

9

issubset(….)

Report whether another set contains this set.

10

issuperset(….)

Report whether this set contains another set.

11

pop()

Remove and return an arbitrary set element that is the last element of the set. Raises KeyError if the set is empty.

12

remove(item)

Remove an element from a set. It must be a member. If the element is not the member of the set, it raises KeyError.

13

symmetric_difference(….)

Remove an element from a set. It must be a member. If the element is not the member of the set, it raises KeyError.

14

symmetric_difference_update(….)

Update a set with symmetric difference of itself and another.

15

union(….)

Return the union of sets as a new set.

16

Update()

Update a set with the union of itself and others.



No comments:

Post a Comment