Python - Set

 Built-in Data Structure -- Set

Introduction to Set

We all are studied Set in our class 10th. The same concept is applied here. All the set operations you will get in this. Stay with me. You will know the Set and able to teach anyone about it.

So, very first question is What is Set?

Let's answer this question later just recall what you know about Set. Think for minute or 5 ......... Tick, Tick, Tick.

Have you recalled it. I guess so. If not leave on me. Kidding. Pay attention here guys. 

  1. Set is an unique collection of item.
  2. Set has no duplicate elements.
  3. It's an unordered data structure.
  4. Since sets are unordered, we cannot access items using indexes like we do in a list and tuple.
  5. Slicing is not possible.
  6. It is Iterable.
  7. It is Mutable.

Creation of Set

  1. Set is created using { } curly bracket or set constructor.
  2. To create an empty set, use set function. As shown in image.


Important Set functions.


As, we all not basic set operations is like, Union, Intersection, Discard, Difference. All these operations can be perform on the python.

  1. Intersection () - set.intersection(set1, set2 ... etc) return the common element between the both sets.
  2. Union() -  The union() method returns a set that contains all items from the original set, and all items from the specified set(s). -- set.union(set1,set2...).
  3. Difference() - The returned set contains items that exist only in the first set, and not in both sets.-- a.difference(b), a and b are both sets.
  4. Issubset() - The issubset() method returns True if all items in the set exists in the specified set, otherwise it returns False.
  5. Discard() - The discard() method removes the specified item from the set. This method is different from the remove() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not    -- set.discard(value).
  6. Remove() - The remove() method removes the specified item from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not  -- set.remove(value).
  7. Pop() - The pop() method removes a random item from a set. -- set.pop()
  8. Clear() - To clear or remove all the elements from a set -- set.clear().
  9. Add() - to add element in a set.  a = {1,2,3} -- a.add(4) -- print(a) -- {4,1,2,3}.
  10. Update() - to add multiple element in a set. a.update({}.

Comments