0% found this document useful (0 votes)
29 views19 pages

9 Set

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views19 pages

9 Set

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Handling Sets in Python

Set

✔ A Set is an unordered collection data type that is iterable, mutable and


has no duplicate elements.
✔ Python’s set class represents the mathematical notion of a set.
✔ To check a specific element is contained in the set or not is carried out
by hash table.
✔ A set itself may be modified, but the elements contained in the set must
be of an immutable type.(lists and dictionaries can not be included)
✔ Sets can not be indexed or sliced.
✔ It is represented with { } with at least one element or set() method.
indexing not allowed
# access individual value
# print(set1[0]) <- error
Set

x={}
print(type(x))
Output
#Using {}
x={2,3} <class 'dict'>
print(type(x)) <class 'set'>
<class 'set'>
#Using set() method
y=set()
print(type(y))

✔ Python interprets empty curly braces ({}) as an empty
dictionary, so the only way to define an empty set is with the
set() function:
set() method
x = set(<iter>)
The argument <iter> is an iterable—i.e. list, tuple or string.

#Using iterables
x = set(['pen', 'pencil', 'book', 'eraser', 'gum'])
print(x)
y = set(('pen', 'pencil', 'book', 'eraser', 'gum'))
print(y)
z=set('hello')
print(z) Output

{'gum', 'pen', 'pencil', 'eraser', 'book'}


Note: elements are displayed unordered and
no duplication allowed. {'gum', 'pen', 'pencil', 'eraser', 'book'}
{'h', 'o', 'e', 'l'}
set with mutable element
We can not keep list and dictionary as elements of a set.

set1={1,[1,2,3]}

Output

Traceback (most recent call last):


File "D:\SBMP\SUBJECTS\Python\Python_Code\sets\set1.py", line 25, in
<module>
set1={1,[1,2,3]}
TypeError: unhashable type: 'list'
size and membership of set

x = {'first', 'second', 'third'}


print(len(x))
print('first' in x)
print('distinction' in x)

Output

3
True
False
set operators and methods Output
x1 = {1, 2, 3,4,5} Union Operation:
x2 = {1,3,6,7,8} {1, 2, 3, 4, 5, 6, 7, 8}
print("Union Operation:") {1, 2, 3, 4, 5, 6, 7, 8}
print(x1 | x2) Intersection Operation:
print(x1.union(x2)) {1, 3}
print("Intersection Operation:") {1, 3}
print(x1 & x2) Difference Operation:
print(x1.intersection(x2)) {2, 4, 5}
print("Difference Operation:") {2, 4, 5}
print(x1 - x2) Symmetric difference Operation:
print(x1.difference(x2)) {2, 4, 5, 6, 7, 8}
print("Symmetric difference Operation:") {2, 4, 5, 6, 7, 8}
print(x1^x2) Disjoint Operation:
print(x1.symmetric_difference(x2)) False
#x1.isdisjoint(x2) returns True if x1 and x2 have no elements in common
print("Disjoint Operation:")
print(x1.isdisjoint(x2))
set operators and meaning

❑ A set x1 is considered a subset of another set x2 if every element of x1 is in x2.

❑ A proper subset is the same as a subset, except that the sets can’t be identical. A
set x1 is considered a proper subset of another set x2 if every element of x1 is in
x2, and x1 and x2 are not equal.

❑ A superset is the reverse of a subset. A set x1 is considered a superset of another


set x2 if x1 contains every element of x2.

❑ A proper superset is the same as a superset, except that the sets can’t be
identical. A set x1 is considered a proper superset of another set x2 if x1 contains
every element of x2, and x1 and x2 are not equal.
set operators and methods
# To check subset
x1 = {1,3}
x2 = {1,3,6,7,8} Output
print("Checking subset")
print(x1.issubset(x2)) Checking subset
print(x1<=x2) True
# To check proper subset
print("Checking proper subset") True
print(x1<x2) Checking proper subset
print(x1<x1) True
x2 = {1,3} False
x1 = {1,3,6,7,8}
Checking superset
# To check superset
print("Checking superset") True
print(x1.issuperset(x2)) True
print(x1>=x2) Checking proper superset
# To check proper superset True
print("Checking proper superset")
False
print(x1>x2)
print(x1>x1)
set operators and methods observations

✔ Although the ^ operator allows multiple sets, the symmetric_difference() method


doesn’t.
✔ There is no operator that corresponds to the .isdisjoint() method.
✔ If isdisjoint() returns False then intersection operation will return nothing.
✔ The < operator is the only way to test whether a set is a proper subset. There is
no corresponding method.
✔ The > operator is the only way to test whether a set is a proper superset. There is
no corresponding method.
set Methods

add() Adds an element to a set.


remove() Removes an element from the set. If element is not existing it raises an
exception.

discard() Removes an element from the set. If element is not existing it doesn’t
raise exception.
clear() Removes all items from the set.
pop() Removes a random element from the set.
update() Modifies a set by union.
intersection_update() Modifies a set by intersection.
difference_update() Modifies a set by difference.
Modifying Sets
x = {'Flash Drive', 'HDD', 'SSD'}
x.add('DVD')
print(x)
#if element is not existing remove() raises
# an exception
x.remove('Flash Drive')
print(x)
#x.remove('RAM') # raises exception
#Does nothing
Output
x.discard('RAM')
print(x) {'DVD', 'HDD', 'Flash Drive', 'SSD'}
#Removes a random element {'DVD', 'HDD', 'SSD'}
x.pop() {'DVD', 'HDD', 'SSD'}
print(x) {'HDD', 'SSD'}
#Clears entire set set()
x.clear()
print(x)
Modifying Sets

x1={1,2,3,4}
#x1.update(x2) and x1 |= x2 add to x1
#any elements in x2 that x1 does not
already have
x1.update([3,5])
print(x1) Output
#Same as x1 &= X2 {1, 2, 3, 4, 5}
x1.intersection_update([3,4]) {3, 4}
print(x1) {3, 4}
#Same as x1 -=x2
x1.difference_update([1,2])
print(x1)
Frozen Sets

✔ frozenset, is in all respects exactly like a set, except that a frozenset is


immutable.
✔ We can perform non-modifying operations on a frozenset.

x = frozenset(['is', 'are', 'were']) frozenset({'is', 'are', 'were'})


print(x) 3
print(len(x)) frozenset({'is'})
print(x & {'is','was'})

Note: We can not apply add(), remove(), pop() and clear() methods.
Frozen Sets

# Augmented operator assignments


f = frozenset(['I', 'We', 'You'])
s = {'We','They','I'} frozenset({'We', 'I'})
f &= s
print(f)

Note: Python does not perform augmented assignments on frozensets in place.


The statement x &= s is effectively equivalent to x = x & s. It isn’t modifying the
original x. It is reassigning x to a new object, and the object x originally referenced
is gone.
We can verify this with the id() function.
Frozen Sets

❑ Frozensets are useful in situations where you want to use a set, but you need
an immutable object. For example, you can’t define a set whose elements are
also sets, because set elements must be immutable.

Traceback (most recent call last):


x1 = set(['Python']) File "D:\SBMP\SUBJECTS\Python\Python_Code\sets\
x2 = set(['is']) frozenset.py", line 4, in <module>
x3 = set(['cool']) x = {x1, x2, x3}
TypeError: unhashable type: 'set'
x = {x1, x2, x3}

x1 = frozenset(['Python']) {frozenset({'Python'}), frozenset({'cool'}),


x2 = frozenset(['is']) frozenset({'is'})}
x3 = frozenset(['cool'])
x = {x1, x2, x3}
print(x)
Frozen Sets

❑ We can not add dictionaries in the set. But using frozenset we can do it.
Traceback (most recent call last):
x = {1, 2, 3} File "D:\SBMP\SUBJECTS\Python\Python_Code\sets\
y = {'a', 'b', 'c'} frozenset.py", line 3, in <module>
d = {x: 'hi', y: 'bye'}
d = {x: 'hi', y: 'bye'} TypeError: unhashable type: 'set'

x = frozenset({1, 2, 3})
y = frozenset({'a', 'b', 'c'})
d = {x: ‘hi', y: ‘bye'}
{frozenset({1, 2, 3}): ‘hi', frozenset({'b', 'a', 'c'}): ‘bye'}
print(d)
THANKS
!
Any questions?
You can find me at
▸ avanishvishwakarma96@gmail.
com

You might also like