- A set is a well defined collection of objects.
- The elements or members of a set can be anything: numbers, characters, words, names, letters of the alphabet, even other sets, and so on.
- A set contains an unordered collection of unique and immutable objects.
- The set data type is, as the name implies, a Python implementation of the sets as they are known from mathematics.
- If we want to create a set, we can call the built-in set function with a sequence or another iterable object.
- Sets are implemented in a way, which doesn’t allow mutable objects.
- Though sets can’t contain mutable objects, sets are mutable:
- Set Operations
- add(element) -> A method which adds an element, which has to be immutable.
- clear() -> All elements will be removed from set.
- copy() -> Creates a shallow copy, which is returned.
- difference() -> This method returns the difference of two or more sets as a new set.
- difference_update() -> The method difference_update removes all elements of another set from this set. x.difference_update(y) is the same as “x = x – y”
- discard(el) -> An element el will be removed from the set, if it is contained in the set. If el is not a member of the set, nothing will be done.
- remove(el) ->works like discard(), but if el is not a member of the set, a KeyError will be raised.
- union(s) -> This method returns the union of two sets as a new set, i.e. all elements that are in either set.
- intersection(s) -> Returns the intersection of the instance set and the set s as a new set. In other words: A set with all the elements which are contained in both sets is returned.
- isdisjoint() -> This method returns True if two sets have a null intersection.
- issubset() -> x.issubset(y) returns True, if x is a subset of y.
- issuperset() -> x.issuperset(y) returns True, if x is a superset of y.
- pop() -> removes and returns an arbitrary set element. The method raises a KeyError if the set is empty.
Start the discussion at discuss.itversity.com