Sets Data Structure in Python

·

2 min read

Sets Data Structure in Python

Defining a set

A set is an unordered collection of unique elements. Sets are enclosed in curly braces {}. They are useful for storing distinct values and performing set operations.

empty_set = set() #Creating an Empty Set 
fruits = {"apple", "banana", "orange"}

add

Elements can be added to a set using the add() method. Duplicates are automatically removed, as sets only store unique values.

fruits.add("mango")

clear()

The clear() method removes all elements from the set, resulting in an empty set. It updates the set in place.

fruits.clear()

copy()

The copy() method creates a shallow copy of the set. Any modifications to the copy won't affect the original set.

new_fruits = fruits.copy()

discard()

Use the discard() method to remove a specific element from the set. Ignores if the element is not found.

fruits.discard("apple")

issubset()

The issubset() method checks if the current set is a subset of another set. It returns True if all elements of the current set are present in the other set, otherwise False.

colors = {"apple"}
fruits = {"apple", "banana", "orange"}
is_subset = colors.issubset(fruits )
# True

issuperset()

The issuperset() method checks if the current set is a superset of another set. It returns True if all elements of the other set are present in the current set, otherwise False.

is_superset = colors.issuperset(fruits)

pop()

The pop() method removes and returns an arbitrary element from the set. It raises a KeyError if the set is empty. Use this method to remove elements when the order doesn't matter.

removed_fruit = fruits.pop()

remove()

Use the remove() method to remove a specific element from the set. Raises a KeyError if the element is not found.

fruits.remove("banana")

update()

The update() method adds elements from another iterable into the set. It maintains the uniqueness of elements.

fruits.update(["kiwi", "grape"])

Set Operations

Perform various operations on sets: union, intersection, difference, symmetric difference.

combined = fruits.union(colors) 
common = fruits.intersection(colors) 
unique_to_fruits = fruits.difference(colors) 
sym_diff = fruits.symmetric_difference(colors)