Open In App

Hash Set in Python

Last Updated : 17 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • Hash Set does not allow duplicate values.
  • Sets in Python are unordered, because the elements are stored based on their hash values, not by their order of insertion.
  • Sets use hashing to provide fast lookups, insertions, and deletions.
  • Hash Set are Mutable. You can add or remove elements after creating the set.
  • Sets can only store hashable elements, like numbers, strings, and tuples (not lists or dictionaries).

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.

  • Use remove() to delete an element (raises an error if it doesn’t exist).
  • Use discard() to delete an element (does not raise an error if the element is missing).
  • Use pop() to remove and return a random element.
Python
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

  • Sets are unordered, so you cannot access elements by index.
  • Sets only store immutable (hashable) elements like numbers, strings, and tuples. Lists and dictionaries cannot be stored in a set.

Refer to this article for detailed explanation – Python Set.





Next Article
Article Tags :
Practice Tags :

Similar Reads