Python Sets-Built Methods

aimtocode

Python Set Definition

A set is an unordered collection data type with no duplicate elements. Sets are iterable and mutable. The elements appear in an arbitrary order when sets are iterated.

The elements of the set can not be duplicate. The elements of the python set must be immutable.


Python Set Built-in Methods

There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with set objects.

Method Description
add()Adds an element to the set
clear()Removes all the elements from the set
copy()Returns a copy of the set
difference()Returns a set containing the difference between two or more sets
difference_update()Removes the items in this set that are also included in another, specified set
discard()Remove the specified item
intersection()Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint()Returns whether two sets have a intersection or not
issubset()Returns whether another set contains this set or not
issuperset()Returns whether this set contains another set or not
pop()Removes an element from the set
remove()Removes the specified element
symmetric_difference()Returns a set with the symmetric differences of two sets
symmetric_difference
_update()
inserts the symmetric differences from this set and another
union()Return a set containing the union of sets
update()Update the set with the union of this set and others


Set Built-in Functions

Function Description
all() Return True if all elements of the set are true (or if the set is empty).
any() Return True if any element of the set is true. If the set is empty, return False.
enumerate() Return an enumerate object. It contains the index and value of all the items of set as a pair.
len() Return the length (the number of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
sorted() Return a new sorted list from elements in the set(does not sort the set itself).
sum() Retrun the sum of all elements in the set.


aimtocode