Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Set in Python

 Set items are unordered, unchangeable,


and do not allow duplicate values.
 It is commonly used in membership
testing, removing duplicates from a
sequence, and computing mathematical
operations such as intersection, union,
difference, and symmetric difference.
 A set is can also be created by placing all the
items (elements) inside curly braces {}.
 It can have any number of items and they may be
of different types (integer, float, tuple, string etc.).
 But a set cannot have a mutable element, like list
or dictionary, as its element.
 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.
 Ex:
s={1,2,3,4,"helllo",(1,2,3)}
print(s)
Output:
{1, 2, 3, 4, (1, 2, 3), 'helllo'}
 Sets are mutable. But since they are
unordered, indexing have no meaning.
 We cannot access or change an element
of set using indexing or slicing. Set does
not support it.
 Duplicate values will be ignored:
 Ex:
s=set([1,2,3,4,1,2,1])
print(s)

Output:
{1, 2, 3, 4}
Iteration Over Sets
 Ex:
s=set([1,2,3,4,1,2,1]) #we can make set from list
for i in s:
print(i)

Output:
1
2
3
4
Adding members in set
 We can add single element using the add() method and
multiple elements using the update() method. The update()
method can take tuples, lists, strings or other sets as its argument.
The elements of the iterable are added to the set.

 Ex:
s=set()
s.add("Red")
print(s)
s.update(["Blue", "Green"])
print(s)

Output:
{'Red'}
{'Red', 'Blue', 'Green'}
 Ex:
s={1,2,3,4,"helllo",(1,2,3)}
s.update([4,5,6],{1,7,8})
print(s)

Output:
{1, 2, 3, 4, 5, 6, 7, 8, (1, 2, 3), 'helllo'}

If dictionaries are passed to the update() method,


the keys of the dictionaries are added to the set.
Removing items from set
The pop() method returns an arbitrary (random)
element from the set. Also, the set is updated and
will not contain the element (which is returned).
 Ex:
s=set([0,1,2,3,1,3,4,2])
print(s)
s.pop() #any item will be popped
print(s)
s.pop()
print(s)
s.remove(3)
print(s)
s.discard(4)
print(s)
Output:
{0, 1, 2, 3, 4}
{1, 2, 3, 4}
{2, 3, 4}
{2, 4}
{2}

- The only difference between the discard() and


remove() is that, while using discard() if the item
does not exist in the set, it remains unchanged.
But remove() will raise an error in such condition.
- clear() method also can be used, to remove
all elements.
Intersection of sets
 Ex:
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
setz = setx & sety
print(setz)
#print(setx & sety)
#print(setx.intersection(sety))

Output:
{'blue'}
Union of sets
 Ex:
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
setz = setx | sety
print(setz)
#print(setx|sety))
#print(setx.union(sety))
Output:
{'green', 'blue', 'yellow'}
Set difference
 If A and B are two sets. The set difference
of A and B is a set of elements that exists only in
set A but not in B.
Ex:
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
setz = setx - sety
print(setz)
#print(setx - sety)
#print(setx.difference(sety))

Output:
{'green'}
issubset and issuperset
The issubset() method returns True if all elements of a set are present in another
set (passed as an argument). If not, it returns False.
The issuperset() method returns True if all items in the specified set exists in the
original set, otherwise it retuns False.
 Ex:
setx = set(["green", "blue"])
sety = set(["blue", "yellow", "green"])
sub = setx <= sety
print(sub)
sup = setx >= sety
print(sup)

Output:
True
False
issubset and issuperset
The issuperset() method returns True if all items in the specified set
exists in the original set, otherwise it retuns False.

 Ex:
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}

z = x.issuperset(y)

print(z)
Output:
True
Isdisjoint()
The isdisjoint() method returns True if two sets are disjoint
sets. If not, it returns False.

 EX:
A={1,2,3,4}
B={3,4}
print(A.issubset(B))
print(A.issuperset(B))
print(A.isdisjoint(B))

Output:
False
True
False
Shallow copy of sets
 Ex:
setx = set(["green", "blue"])
sety = set(["blue", "yellow", "green"])
c = setx.copy()
print(c)

Output:
{'blue', 'green'}
Set Membership Test
 We can test if an item exists in a set or not,
using the keyword in.
 Ex:
A = set("apple")
print('a' in A)
print('p' not in A)
Output:
True
False
Built-in Functions with Set
Frozenset
 Frozenset is has the characteristics of a
set, but its elements cannot be changed
once assigned.
 While tuples are immutable lists, frozensets
are immutable sets.
 Frozensets can be used as keys
in Dictionary or as elements of another
set.
 Frozensets can be created using the
function frozenset().
 Ex:
A = frozenset("apple")
 This datatype supports methods like
copy(), difference(), intersection(),
isdisjoint(), issubset(), issuperset(),
symmetric_difference() and union().
 Being immutable it does not have method
that add or remove elements.
# random dictionary
 person = {"name": "John", "age": 23, "sex": "male"}
 fSet = frozenset(person)
 print('The frozen set is:', fSet)

Output:

The frozen set is: frozenset({'name', 'sex', 'age'})

You might also like