A Hash Set is a data structure that stores unique elements and provides efficient operations for adding, removing, and checking elements. Python's built-in set data type is an implementation of a hash set.
hs = {1, 2, 3, 4}
print(hs)
Output
{1, 2, 3, 4}
Explanation:
- hs is created using curly braces.
- The collection contains unique elements.
- Hashing is used to efficiently store and find elements.
Important points:
- Duplicate values are automatically removed.
- Elements cannot be accessed using indexes.
- The collection can be modified after creation.
- Only hashable objects can be stored as elements.
- Hashing provides efficient insertion, deletion, and membership checking.
Creating a Hash Set
A hash set can be created using curly braces {} or the set() constructor. The set() constructor can convert an iterable such as a list into a hash set.
hs = set([1, 2, 3, 3, 4])
print(hs)
Output
{1, 2, 3, 4}
Explanation:
- The list contains 3 twice.
- set() converts the list into a hash set.
- The duplicate occurrence of 3 is removed
Operations on Hash Set
1. Adding Elements
The add() method is used to insert an element into a hash set.
hs = {1, 2, 3}
hs.add(4)
print("After Adding 4:", hs)
Output
After Adding 4: {1, 2, 3, 4}
Explanation:
- hs initially contains three elements.
- add(4) inserts 4 into the collection.
- The updated collection contains four elements.
2. Removing Elements
The remove() and discard() methods are used to delete elements.
hs = {1, 2, 3, 4}
hs.remove(2)
hs.discard(5)
print(hs)
Output
{1, 3, 4}
Explanation:
- remove(2) deletes 2 from the collection.
- discard(5) does not raise an error because 5 is not present.
- remove() raises a KeyError if the specified element does not exist.
- discard() does not raise an error when the element is missing.
3. Using pop()
The pop() method removes and returns an arbitrary element.
hs = {1, 2, 3}
item = hs.pop()
print("Removed:", item)
print("Remaining:", hs)
Output
Removed: 1
Remaining: {2, 3}
Explanation:
- pop() removes one element from the collection.
- The removed element is stored in item.
- The removed element should not be assumed to be a specific value because the collection is unordered.
4. Checking for an Element
The in operator is used to check whether an element exists.
hs = {10, 20, 30}
print(20 in hs)
Output
True
Explanation:
- 20 in hs checks whether 20 exists in the collection.
- Since 20 is present, the expression returns True.