Set
I LOVE DOING THIS :)
A set is an unordered collection data type with No Duplicate elements, they are Iterable and Mutable.
The elements appear in an arbitrary order when sets are iterated
Sets are commonly used for removing duplicates entries, and also for operations such as intersection, union, and set difference
How to Create Sets
Sets can be created by calling the built-in set()
function with a sequence
Creating a set with a list []
Creating a set with numbers and seeing how it strips away the duplicates
Creating a set with strings and removing the duplicates
Methods to Change a Set
Add elements to a Set
We can add a tuple (9, 10) to the d0p
and the new set will consist of the tuple
Similarly, we can update our current set using d0p.update([11, 12])
We can literally update our set using a list or tuple or a dictionary too
Remove elements from a Set
We can remove an element from the set using these two methods called .discard
and .remove
The only key difference between discard and remove is that discard doesn't throw any error if the element isn't present but whereas remove will raise a KeyError Exception
Few more Set Methods
copy()
- Creates a shallow copy of the set with which it is called
pop()
- Removes an arbitrary set elementclear()
- Will remove all the elements in the set
Last updated