Unordered Sets In Python

unordered

Introduction to Unordered Sets 

 An unordered sets, a dynamic and efficient unordered associative container designed for optimal performance in programming. An unordered_set is crafted using a hash table, where keys are strategically hashed into indices, ensuring that insertions are consistently randomized. 

Let’s jump into the article to know more about Unordered Sets in Python .

Understanding Unordered Sets

Unordered set, often referred to simply as a “set,” is a data structure in computer science that stores a collection of distinct elements. The term “unordered” means that the elements in the set have no specific order, and the order in which elements are added to the set is not preserved.

Unordered Sets Python with Example

unordered_sets_python_2

Unordered Sets Techniques

When working with unordered sets, there are several techniques and operations that you might find useful. Here are some common techniques and operations associated with unordered sets:

1. Adding Elements:

Use the add method to insert a new element into the set.

my_set = {1, 2, 3}
my_set.add(4)

2. Removing Elements:

Use the remove method to remove a specific element from the set. If the element is not present, it raises a KeyError. Alternatively, you can use the discard method, which removes the element if it’s present, but does nothing if the element is not in the set.

my_set = {1, 2, 3}
my_set.remove(2)
# or
my_set.discard(3)

3. Checking Membership:

Use the in operator to check if an element is present in the set.

my_set = {1, 2, 3}
print(2 in my_set)  # True

4. Set Operations:

Unordered sets support various set operations such as union (|), intersection (&), difference (-), and symmetric difference (^).

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union_set = set1 | set2
intersection_set = set1 & set2
difference_set = set1 - set2
symmetric_difference_set = set1 ^ set2

 5. Iterating Over Elements:

You can use a for loop to iterate over the elements of a set. However, keep in mind that the order of elements is not guaranteed.

my_set = {1, 2, 3}
for element in my_set:
print(element)

6. Copying Sets:

To create a copy of a set, you can use the copy method or simply use the set constructor.

original_set = {1, 2, 3}
copied_set = original_set.copy()
# or
copied_set = set(original_set)

7. Set Comprehensions:

Similar to list comprehensions, you can use set comprehensions to create sets in a concise manner.

squares_set = {x**2 for x in range(1, 6)}

8. Conversion to Sets:

You can convert other iterable types (lists, tuples) to sets using the set constructor.

my_list = [1, 2, 3, 2]
converted_set = set(my_list)  # Results in {1, 2, 3}

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Unordered Set

unordered set is a collection of unique elements without a specific order, allowing fast membership testing and dynamic size adjustments. Examples include Python’s set and C++’s std::unordered_set.

Implementation of Unordered Set In Python

Run
# Creating an unordered set
my_set = {1, 2, 3, 4, 5}

# Adding elements to the set
my_set.add(6)
my_set.add(2)  # Duplicate elements are not added

# Removing an element from the set
my_set.remove(3)

# Checking membership
print(2 in my_set)  # True
print(7 in my_set)  # False

# Iterating over elements
print("Elements in my_set:")
for element in my_set:
    print(element)

# Set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

union_set = set1 | set2
intersection_set = set1 & set2
difference_set = set1 - set2
symmetric_difference_set = set1 ^ set2

print("\nSet Operations:")
print("Union:", union_set)
print("Intersection:", intersection_set)
print("Difference (set1 - set2):", difference_set)
print("Symmetric Difference:", symmetric_difference_set)

# Set comprehension
squares_set = {x**2 for x in range(1, 6)}
print("\nSquares Set:", squares_set)

# Copying a set
copied_set = my_set.copy()
print("Copied Set:", copied_set)

# Converting other iterables to sets
my_list = [1, 2, 3, 2]
converted_set = set(my_list)
print("Converted Set from List:", converted_set)

Output:

True
False
Elements in my_set:
1
2
4
5
6

Set Operations:
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference (set1 - set2): {1, 2}
Symmetric Difference: {1, 2, 5, 6}

Squares Set: {1, 4, 9, 16, 25}
Copied Set: {1, 2, 4, 5, 6}
Converted Set from List: {1, 2, 3}

Explanation : 

In this Python code, we’ve created a simple HashTable class with methods for insertion, search, and deletion using linear probing for collision resolution.

  • Creation: Use {} to create an unordered set in Python.
  • Adding Elements: Utilize the add method for inserting elements.
  • Removing Elements: Use remove or discard to eliminate elements.
  • Membership Testing: Employ in to check if an element is present.
  • Iterating: Use a for loop for iteration (order not guaranteed).
  • Set Operations: Perform set operations like union (|) and intersection (&).
  • Comprehension: Create sets using comprehensions, e.g., {x**2 for x in range(1, 6)}.
  • Copying Sets: Use copy method or set constructor for duplication.

Time and Space Complexity:

OperationTime ComplexitySpace Complexity
Basic Set Operations (add, remove, membership, copy)O(1) averageO(n)
Set Operations (union, intersection, difference, symmetric difference)O(len(set1) + len(set2))O(len(set1) + len(set2))

Advantages of Unordered Sets

Final Thoughts

unordered sets provide a versatile and efficient data structure in programming. With their emphasis on fast membership testing, enforcement of element uniqueness, and support for various mathematical set operations, sets offer a valuable tool for managing collections of distinct elements.

The absence of a specific order, dynamic sizing capabilities, and efficient implementations contribute to their flexibility and performance. Whether performing set operations or simplifying logic by relying on unordered elements, sets prove to be advantageous in a variety of programming scenarios.

FAQs

An unordered set in Python is a built-in data structure that stores unique elements without maintaining any specific order. It is defined using curly braces {} or the set() function.

No, Python sets do not allow duplicates. If a duplicate is added, it will be ignored, and the set will retain only unique values.

Sets are unordered because the elements do not maintain the order in which they were added. This allows for faster operations like lookup and deletion.

Set membership is checked using the in keyword, which is highly efficient due to the underlying hash table implementation. For example: if 5 in my_set:.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription