Sets in Python
Sets
A set is unordred collection of items with no duplicate. It can be used to eliminating duplicates or membership testing.
Set also supports union, intersection, difference and symmetric difference. Set can be initialized using set().
Set can be initialized using set().set1 = set()
Set has following methods
set.add(element)
Add element to set. If element already present nothing happens.set.clear()
Remove all elements and clear the set.set.copy()
Returns shallow copy set.set.difference(another_set[s])
Returns the difference of two or more sets as new set.set.difference_update(another_set)
Remove all elements of another from this set.set.discard(element)
Remove an element from set if is a member.set.intersection(another_set[s])
Returns the intersection of two or more sets as new set.set.intersection_update(another_set)
Update a set with the intersection of itself and another.set.isdisjoint(another_set)
Return True if two sets have null intersection, means that Returns true if the set have elements otherwise False.set.issubset(super_set)
Check whether super set contains this set. It Returns True if super set has all elements of this set and False Otherwise.set.issuperset(sub_set)
Check whether this set contains another set. It Returns True if this set has all elements of the sub set and False Otherwise.set.pop()
Remove and return an arbitrary set element and Raises KeyError if set is empty.set.remove(element)
Remove an element from if it is member and If the element is not a member, raise KeyError.set.symmetric_difference(another_set)
Returns the symmetric difference of two sets as a new set. i.e. All elements that are in exactly in one of the sets.set.symmetric_difference_update(another_set)
Update a set with the symmetric difference of itself and another.set.union(another_set)
Returns the union of sets as a new set. i.e. All elements that are in either set.set.update(another_set)
Update a set with the union of itself and another set.Let's understand this by example code
>>> x=set() >>> x.add(3) >>> x.add(7) >>> x.add(9) >>> x set([3, 7, 9]) >>> l = [3, 5, 8, 9, 11, 19] >>> y = set(l) >>> y set([3, 5, 8, 9, 11, 19]) >>> z=y.copy() >>> z set([19, 3, 5, 8, 9, 11]) >>> x.difference(y) set([7]) >>> z.discard(5) >>> z set([19, 3, 8, 9, 11]) >>> y.intersection(x) set([9, 3]) >>> x.isdisjoint(y) False >>> z.issubset(y) True >>> y.issuperset(x) False >>> z.pop() 19 >>> y.remove(8) >>> x.symmetric_difference(z) set([8, 11, 7]) >>> x.union(y) set([3, 5, 7, 9, 11, 19]) >>> x set([9, 3, 7]) >>> y set([3, 5, 9, 11, 19]) >>> z.clear() >>> z set([]) >>> x&y set([9, 3]) >>> x|y set([3, 5, 7, 9, 11, 19]) >>> y-x set([19, 11, 5]) >>> y^x set([19, 11, 5, 7])
Keep Following, For More.
Comments
Post a Comment