Python Set Methods
A set is an unordered and unindexed collection of items. Set has no duplicates.It can also used to perform mathematical set operations.
Method | Description |
---|---|
add() | Used to add element to the set. |
clear() | Used to Remove all the elements from the set. |
copy() | Used to return copy of the set. |
difference() | Returns the difference of two or more sets as a new set [A-B] |
difference_update() | Used to update the difference itself. |
discard() | Used to remove an element from the set. |
isdisjoint() | Returns True if two sets have no common elements. |
issubset() | Returns True if a set has all elements of another set. |
issuperset() | Returns True if another set has all elements of this set. |
intersection() | Used to return a new set that contains intersection of two sets. |
intersection_update() | Used to update the intersection itself. |
pop() | Used to remove a random element from the set. |
remove() | Used to remove the element of the given value. |
symmetric_difference() | Used to return a new set that contains symmetric difference of two sets.[ (B−A) U (A−B)] |
symmetric_difference_update() | Used to update the symmetric difference itself. |
union() | Used to return a new set that contains union of two sets.. |
update() | Update the set with union of another set. |
a={1,5,6,4,8} a.add(7) print(a)
{1, 4, 5, 6, 7, 8}
a={1,5,6,4,8} a.clear() print(a)
set()
a={1,5,6,4,8} b=a.copy() print(b)
{1, 4, 5, 6, 8}
a={1,2,3,4,5} b={4,5,6,7,8} print(a.difference(b)) print(b.difference(a))
{1, 2, 3}
{8, 6, 7}
{8, 6, 7}
a={1,2,3,4,5} b={4,5,6,7,8} a.difference_update(b) print(a)
{1, 2, 3}
a={1,2,3,4,5} a.discard(3) print(a)
{1, 2, 4, 5}
a={1,2,3} b={4,5,6,7,8} print(a.isdisjoint(b))
True
a={1,2,3} b={4,5,6,7,8} print(a.isdisjoint(b))
True
a={3,4,5} b={1,2,3,4,5,6,7} print(a.issubset(b))
True
a={1,2,3,4,5,6,7} b={3,4,5} print(a.issuperset(b))
True
a={1,2,3,4,5} b={4,5,6,7,8} print(a.intersection(b))
{4, 5}
a={1,2,3,4,5} b={4,5,6,7,8} a.intersection_update(b) print(a)
{4, 5}
a={1,2,3,4,5} a.pop() print(a)
{2, 3, 4, 5}
a={1,2,3,4,5} a.remove(3) print(a)
{1, 2, 4, 5}
a={1,2,3,4,5} b={4,5,6,7,8} print(a.symmetric_difference(b))
{1, 2, 3, 6, 7, 8}
a={1,2,3,4,5} b={4,5,6,7,8} a.symmetric_difference_update(b) print(a)
{1, 2, 3, 6, 7, 8}
a={1,2,3,4,5} b={4,5,6,7,8} print(a.union(b))
{1, 2, 3, 4, 5, 6, 7, 8}
a={1,2,3,4,5} b={4,5,6,7,8} a.update(b) print(a)
{1, 2, 3, 4, 5, 6, 7, 8}