Python Sets
Hello guys, we are going to learn all about Python sets. Set is a collection of
unordered items. Basically, set has all its elements unique, i.e. no
duplicates.
Initializing
Sets
A set is created by placing
all the elements between the {}
braces. Conversion of list into tuple is also possible.
Output
We should be careful while initializing an empty set. Initializing empty {}
Updating sets
Sets are mutable but we cannot change or access elements
are sets are unordered so there is no discussion about indexing.
However, we can add elements in a set. For adding one
element at a time, we use add() and update() takes lists, strings, lists or
any other set into the existing set. In both the cases, duplication is not
allowed.
Output
Removing of
elements
A particular item can be removed using remove() and discard().
Output
We can also remove an element using pop() but it will pop out randomly. We can also remove the every element by clear().
Predict the output.
Set Operations
Similar to math sets in python also work out
operations like:-
- 1) Union
Union in python is performed by | this operator. This also can be done by union().
Output
- 2)
Intersection
Intersection in python is performed
by & this operator. This also can be done by intersection()
Output
- 3)
Difference
Difference of the set B from set A(A
- B) is a set of elements that are only in A but not in B. Similarly, B - A is
a set of elements in B but not in A.
Difference is performed by – this operator. The same can be done
by difference()
Output
- 4) Symmetric Difference
Symmetric Difference of A and B is a
set of elements in A and B but not in both (excluding the intersection).
Symmetric difference is performed by ^ this operator. Also the same can be
done by symmetric_difference()
Try it out by your own, for better understanding.
Few we have discussed earlier above
Method |
Description |
copy() |
Returns a copy of the set |
difference_update() |
Removes all elements of another
set from this set. Return none indicating the set is mutated. |
intersection() |
Returns the intersection of two
sets as a new set |
intersection_update() |
Updates the set with the
intersection of itself and another |
isdisjoint() |
Returns True if two sets have a
null intersection |
issubset() |
Returns True if another set
contains this set |
issuperset() |
Returns True if this set contains
another set |
symmetric_difference_update() |
Updates a set with the symmetric
difference of itself and another |
Frozenset
Sets being mutable are unhashable, so they can't be
used as dictionary keys. On the other hand, frozensets are hashable and can be
used as keys to a dictionary.
Its syntax is just the same as
sets,
a = frozenset([1,2,3,4,5])
If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via Instagram "@coding.winds".
Do subscribe to our daily blog update by clicking here.
Thank You!