Previous Next

Python Sets

Sets are an unordered list of data elements. They contain more than one item in a single variable. Set items are comma-separated and contained within curly braces {}.

Example:

set1 = {2, 6, 14}
print(set1)

Output

{2, 6, 14}

Add set Items

To insert a single item into a set, employ the add() method.

Example:

fruits = {"Apple", "Orange", "Mango"}
fruits.add("Banana")
print(fruits)

Output

{'Banana', 'Orange', 'Mango', 'Apple'}

Update Set

To insert items from another set into the current set, employ the update() method.

Example:

fruits = {"Apple", "Orange", "Mango"}
fruits2 = {"Lemon", "Grape", "Litchi"}

fruits.update(fruits2)

print(fruits)

Output

{'Lemon', 'Orange', 'Grape', 'Mango', 'Apple', 'Litchi'}

Remove items from set

To delete an item from a set, employ the remove() and discard() methods.

Example 1:

fruits = {"Apple", "Orange", "Mango"}
fruits.remove("Mango")
print(fruits)

Output

{'Orange', 'Apple'}

Example 2:

fruits = {"Apple", "Orange", "Mango"}
fruits.discard("Orange")
print(fruits)

Output

{'Mango', 'Apple'}

Set Methods

Python offers a number of in-built methods to handle sets.

isdisjoint()

The isdisjoint() method verifies whether elements of a specified set exist in another set.

Example:

fruits = {"Apple", "Orange", "Mango"}
fruits2 = {"Apple", "Orange", "Mango"}
print(fruits.isdisjoint(fruits2))

Output:

False

issuperset()

The issuperset() method verifies whether all the elements of the specified set exist in the original set.

Example:

fruits = {"Apple", "Orange", "Mango"}
fruits2 = {"Apple", "Mango"}
print(fruits.issuperset(fruits2))

Output:

True

issubset()

The issubset() method verifies whether all the elements of the original set exist in the specified set.

Example:

fruits = {"Apple", "Orange", "Mango"}
fruits2 = {"Orange", "Mango"}
print(fruits2.issubset(fruits))

Output:

True
Previous Next