How To Use Python Set Collection With Examples

Python, a versatile and popular programming language, offers a variety of data structures to manage and manipulate data efficiently. One such data structure is the set. Sets are unordered collections of unique elements, making them valuable for various tasks like removing duplicates, testing membership, and performing set operations. In this article, we will explore the fundamentals of using Python sets with illustrative examples.

1. Creating a Set.

  1. To create a set in Python, you can use curly braces `{}` or the built-in `set()` constructor.
  2. Here’s how to create a set:
    # Using curly braces
    my_set = {1, 2, 3}
    
    # Using the set() constructor
    another_set = set([4, 5, 6])
  3. Output.
    >>> my_set
    {1, 2, 3}
    >>>
    >>> another_set
    {4, 5, 6}
  4. Remember that sets can only contain unique elements. Any duplicates will be automatically removed.
  5. Suppose you create a set using the below source code, they contains the same values.
    >>> my_frozen_set = frozenset([1,2,3])
    >>>
    >>> my_frozen_set
    frozenset({1, 2, 3})
    >>> my_frozen_set = frozenset([1,1,2,3,3])
    >>>
    >>> my_frozen_set
    frozenset({1, 2, 3})
    >>>
    >>> my_frozen_set = frozenset([1,1,2,3,3,3,4,5,5,5,6,6])
    >>>
    >>> my_frozen_set
    frozenset({1, 2, 3, 4, 5, 6})
    >>>
    >>>
    >>> my_frozen_set = frozenset([2,3,3,3,4,5,5,5,6,6,1,1,1])
    >>>
    >>> my_frozen_set
    frozenset({1, 2, 3, 4, 5, 6})

2. Adding and Removing Elements.

2.1 Adding Elements.

  1. You can add elements to a set using the `add()` method.
  2. Here’s an example:
    my_set = {1, 2, 3}
    my_set.add(4)
    print(my_set)
  3. Now, `my_set` contains `{1, 2, 3, 4}`.

2.2 Removing Elements.

  1. To remove elements from a set, you can use methods like `remove()` and `discard()`.
  2. The difference between these methods is that `remove()` raises an error if the element is not found, whereas `discard()` does not.
    my_set = {1, 2, 3, 4}
    my_set.remove(3)
    my_set.discard(5)  # No error is raised
    
  3. Output.
    >>> my_set = {1, 2, 3, 4}
    >>> my_set.remove(3)
    >>> my_set.discard(5)  # No error is raised
    >>>
    >>> my_set
    {1, 2, 4}
    >>>
    >>> my_set.remove(5)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 5

3. Set Operations.

  1. Python sets support various set operations, such as union, intersection, difference, and symmetric difference.
  2. Let’s explore each of these operations with examples:

3.1 Union.

  1. The union of two sets returns a new set containing all unique elements from both sets.
    set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    union_set = set1.union(set2)
    # or equivalently
    union_set = set1 | set2
  2. Now, `union_set` contains `{1, 2, 3, 4, 5}`.

    >>> set1 = {1, 2, 3}
    >>> set2 = {3, 4, 5}
    >>> union_set = set1.union(set2)
    >>> # or equivalently
    >>> union_set = set1 | set2
    >>>
    >>> union_set
    {1, 2, 3, 4, 5}

3.2 Intersection.

  1. The intersection of two sets returns a new set containing elements that are common to both sets.
    set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    intersection_set = set1.intersection(set2)
    # or equivalently
    intersection_set = set1 & set2
  2. Now, `intersection_set` contains `{3}`.

    >>> set1 = {1, 2, 3}
    >>> set2 = {3, 4, 5}
    >>> intersection_set = set1.intersection(set2)
    >>> # or equivalently
    >>> intersection_set = set1 & set2
    >>>
    >>> intersection_set
    {3}

3.3 Difference.

  1. The difference of two sets returns a new set containing elements that are in the first set but not in the second set.
    set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    difference_set = set1.difference(set2)
    # or equivalently
    difference_set = set1 - set2
  2. Now, `difference_set` contains `{1, 2}`.

    >>> set1 = {1, 2, 3}
    >>> set2 = {3, 4, 5}
    >>> difference_set = set1.difference(set2)
    >>> # or equivalently
    >>> difference_set = set1 - set2
    >>>
    >>> difference_set
    {1, 2}

3.4 Symmetric Difference.

  1. The symmetric difference of two sets returns a new set containing elements that are in either of the sets but not in their intersection.
    set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    symmetric_difference_set = set1.symmetric_difference(set2)
    # or equivalently
    symmetric_difference_set = set1 ^ set2
  2. Now, `symmetric_difference_set` contains `{1, 2, 4, 5}`.

    >>> set1 = {1, 2, 3}
    >>> set2 = {3, 4, 5}
    >>> symmetric_difference_set = set1.symmetric_difference(set2)
    >>> # or equivalently
    >>> symmetric_difference_set = set1 ^ set2
    >>>
    >>> symmetric_difference_set
    {1, 2, 4, 5}

3.5 Membership Testing.

  1. Sets are efficient for membership testing, i.e., checking if an element exists in a set.
  2. You can use the `in` keyword for this purpose.
    my_set = {1, 2, 3, 4, 5}
    print(3 in my_set)  # True
    print(6 in my_set)  # False
  3. Output.
    >>> my_set = {1, 2, 3, 4, 5}
    >>> print(3 in my_set)  # True
    True
    >>> print(6 in my_set)  # False
    False

3.6 Set Comprehensions.

  1. Similar to list comprehensions, Python also supports set comprehensions to create sets in a concise and readable way.
    squared_numbers = {x ** 2 for x in range(1, 6)}
    # squared_numbers is now {1, 4, 9, 16, 25}
  2. Output.
    >>> squared_numbers = {x ** 2 for x in range(1, 6)}
    >>> # squared_numbers is now {1, 4, 9, 16, 25}
    >>>
    >>> squared_numbers
    {1, 4, 9, 16, 25}

4. Other Python Sets Operation Methods.

4.1 `clear()`.

  1. The `clear()` method removes all elements from a set, leaving it empty.
    my_set = {1, 2, 3}
    my_set.clear()
  2. Now, my_set is an empty set: set().

4.2 `copy()`.

  1. The `copy()` method creates a shallow copy of a set.
    original_set = {1, 2, 3}
    copied_set = original_set.copy()
  2. Output.
    >>> original_set = {1, 2, 3}
    >>> copied_set = original_set.copy()
    >>>
    >>> copied_set
    {1, 2, 3}

4.3 `pop()`.

  1. The `pop()` method removes and returns an arbitrary element from the set.
  2. Since sets are unordered, the popped element may not be the same every time.
    my_set = {1, 2, 3, 4, 5}
    popped_element = my_set.pop()
    # popped_element can be any element from the set
  3. Output.
    >>> my_set = {1, 2, 3, 4, 5}
    >>> popped_element = my_set.pop()
    >>> # popped_element can be any element from the set
    >>>
    >>> popped_element
    1
    >>> my_set
    {2, 3, 4, 5}

4.4 `update()`.

  1. The `update()` method adds all elements from another iterable (e.g., a list, tuple, or set) to the current set.
    set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    set1.update(set2)
    # Now, set1 contains {1, 2, 3, 4, 5}
  2. Output.
    >>> set1 = {1, 2, 3}
    >>> set2 = {3, 4, 5}
    >>> set1.update(set2)
    >>> # Now, set1 contains {1, 2, 3, 4, 5}
    >>>
    >>> set1
    {1, 2, 3, 4, 5}

4.5 `intersection_update()`.

  1. The `intersection_update()` method updates the set with the intersection of itself and another iterable.
    set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    set1.intersection_update(set2)
    # Now, set1 contains {3}
  2. Output.
    >>> set1 = {1, 2, 3}
    >>> set2 = {3, 4, 5}
    >>> set1.intersection_update(set2)
    >>> # Now, set1 contains {3}
    >>>
    >>> set1
    {3}

4.6 `difference_update()`.

  1. The `difference_update()` method updates the set with the difference between itself and another iterable.
    set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    set1.difference_update(set2)
    # Now, set1 contains {1, 2}
  2. Output.
    >>> set1 = {1, 2, 3}
    >>> set2 = {3, 4, 5}
    >>> set1.difference_update(set2)
    >>> # Now, set1 contains {1, 2}
    >>>
    >>> set1
    {1, 2}

4.7 `symmetric_difference_update()`.

  1. The `symmetric_difference_update()` method updates the set with the symmetric difference between itself and another iterable.
    set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    set1.symmetric_difference_update(set2)
    # Now, set1 contains {1, 2, 4, 5}
  2. Output.
    >>> set1 = {1, 2, 3}
    >>> set2 = {3, 4, 5}
    >>> set1.symmetric_difference_update(set2)
    >>> # Now, set1 contains {1, 2, 4, 5}
    >>>
    >>> set1
    {1, 2, 4, 5}

4.8 `issubset()` and `issuperset()`.

  1. These methods allow you to check if one set is a subset or superset of another set.
    set1 = {1, 2}
    set2 = {1, 2, 3, 4}
    is_subset = set1.issubset(set2)  # True
    is_superset = set2.issuperset(set1)  # True
  2. Output.
    >>> set1 = {1, 2}
    >>> set2 = {1, 2, 3, 4}
    >>> is_subset = set1.issubset(set2)  # True
    >>> is_superset = set2.issuperset(set1)  # True
    >>>
    >>> is_subset
    True
    >>> is_superset
    True

4.9 `isdisjoint()`.

  1. The `isdisjoint()` method checks if two sets have no common elements.
    set1 = {1, 2, 3}
    set2 = {4, 5, 6}
    are_disjoint = set1.isdisjoint(set2)  # True
  2. Output.
    >>> set1 = {1, 2, 3}
    >>> set2 = {4, 5, 6}
    >>> are_disjoint = set1.isdisjoint(set2)  # True
    >>>
    >>> are_disjoint
    True

5. Conclusion.

  1. Python sets are versatile data structures that allow you to work with collections of unique elements efficiently.
  2. They are particularly useful for various tasks like removing duplicates, performing set operations, and membership testing.
  3. Understanding how to create, modify, and operate on sets is an essential skill for any Python developer.
  4. By following the examples in this article, you should have a solid foundation for working with sets in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.