Hash Set in Python (original) (raw)

Last Updated : 23 Jul, 2025

Hash Set is a data structure that stores unique elements in an unordered manner and provides highly efficient operations for searching, inserting, and deleting elements. Python Set data type is a built-in implementation of a hash set.

Python sets are implemented using hash tables, where each element is stored as a key in the table with an associated value of _None. Hashing ensures that the set operations like add, remove, and lookup are highly efficient, in a constant time O(1).

**Important points:

Creating a Hash Set in Python

You can create a set using curly braces {} or the set() constructor.

Python `

Creating a hash set

hs = {1, 2, 3, 4, 5} print("Hash Set:", hs)

Using set() function

hs1 = set([1, 2, 3, 3, 4]) print("Another Hash Set:", hs1)

`

Basic Operations on Python Hash Set

Adding Elements:

Use the add() method to insert an element into the set.

Python `

hs = {1, 2, 3} hs.add(4) print("After Adding 4:", hs)

`

Removing Elements:

You can se these methods to remove items from a set.

hs = {1, 2, 3, 4} hs.remove(2) hs.discard(5) # No error even though 5 is not in the set print("After Removing:", hs)

removed_item = hs.pop() print("Popped Element:", removed_item) print("Remaining Set:", hs)

`

Limitations of Hash Sets

Refer to this article for detailed explanation - Python Set.