VOOZH about

URL: https://www.geeksforgeeks.org/python/hash-set-in-python/

⇱ Hash Set in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Hash Set in Python

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:

  • 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.


Basic Operations on Python Hash Set

Adding Elements:

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


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.


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.



Comment
Article Tags:
Article Tags: