How to Work with Sets in Python

Sets are a fundamental data structure in Python, offering a collection of unique elements with support for various mathematical operations. This article will guide you through creating sets, performing set operations, and handling sets efficiently.

1. Python Set Basic.

1.1 Creating Sets.

Sets can be created using the `set()` function or with set literals enclosed in curly braces `{}`. Let’s explore some examples:

def creating_sets():
    # Using set() function
    set_example = set([2, 2, 2, 1, 3, 3])

    # Using set literal
    set_example_literal = {6, 5, 6, 4, 5, 3, 1, 2}

    print(set_example) 
    print(set_example_literal)

1.2 Modify Set Elements.

No you cannot directly modify existing elements within a set in Python. Sets are designed to be unordered collections of unique elements, meaning their elements are immutable once added. The below code will throw the error TypeError: ‘set’ object does not support item assignment.

def modify_set_element():
    my_data = [1, 2, 3, 4, 5, 6]
    my_set = set(my_data)
    print(my_set)

    my_set[0] = 9

However, you have several options to add or remove elements from a set.

1.3 Adding Elements.

add() method: This method adds a single element to the set. If the element is already present, nothing happens.

def add_set_element():
    my_set = {1, 2, 3}
    my_set.add('hello')

    # my_set.add([4, 5, 6]) # throw TypeError: unhashable type: 'list'
    my_set.add((4, 5, 6)) #

    my_set.add(1)
    print(my_set)

1.4 Update Set.

update() method: This method adds elements from an iterable (like a list, tuple, or another set) to the set. It performs a union operation, adding unique elements from the iterable.

def update_set():
    my_set = {1, 2, 3}
    my_set.update([4, 5, 2])
    print(my_set)  # Output: {1, 2, 3, 4, 5}

1.5 Remove Elements.

remove() method: This method removes the specified element from the set. If the element is not present, it raises a KeyError.

def remove_set_element():
    my_set = {1, 2, 3}
    my_set.remove(2)
    # my_set.remove(5) # throw KeyError
    print(my_set)  # Output: {1, 3}

1.6 Discard Elements.

discard() method: This method is similar to remove() but does not raise an error if the element is not present.

def discard_set_element():
    my_set = {1, 2, 3}
    my_set.discard(3)
    my_set.discard(4)
    print(my_set)  # Output: {1, 2, 3}

1.7 Check Set Element Existence.

def check_set_element_exist():
    my_set = {1, 2, 3}
    print(1 in my_set)
    print('hello' in my_set)

1.8 Loop Set Elements.

def loop_set_elements():

    my_set = {1, 2, 3}

    for element in my_set:

        print(element)

2. Set Operations.

2.1 Union.

The union of two sets contains all unique elements from both sets. You can perform union using the `union()` method or the `|` operator.

def set_union():
    set_a = {1, 2, 3, 4, 5}
    set_b = {3, 4, 5, 6, 7, 8}

    # Using union method
    union_result = set_a.union(set_b)

    # Using | operator
    union_operator_result = set_a | set_b

    print(union_result) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
    print(union_operator_result) # Output: {1, 2, 3, 4, 5, 6, 7, 8}

2.2 Intersection.

The intersection of two sets contains elements present in both sets. You can perform an intersection using the `intersection()` method or the `&` operator.

def set_intersection():

    set_a = {1, 2, 3, 4, 5}
    set_b = {3, 4, 5, 6, 7, 8}

    # Using intersection method
    intersection_result = set_a.intersection(set_b)

    # Using & operator
    intersection_operator_result = set_a & set_b

    print(intersection_result) # Output: {3, 4, 5}
    print(intersection_operator_result) # Output: {3, 4, 5}

2.3 Difference.

The difference between two sets contains elements from the first set that are not in the second set. You can perform difference using the `difference()` method or the `` operator.

def set_difference():

    set_a = {1, 2, 3, 4, 5}
    set_b = {3, 4, 5, 6, 7, 8}

    # Using difference method
    difference_result = set_a.difference(set_b)

    # Using - operator
    difference_operator_result = set_b - set_a
    #difference_operator_result = set_b.difference(set_a)

    print(difference_result)
    print(difference_operator_result)

2.4 Symmetric Difference.

The symmetric difference of two sets contains elements present in either set, but not in both. You can perform symmetric difference using the `symmetric_difference()` method or the `^` operator.

def set_symmetric_difference():

    set_a = {1, 2, 3, 4, 5}
    set_b = {3, 4, 5, 6, 7, 8}

    # Using symmetric_difference method
    symmetric_difference_result = set_a.symmetric_difference(set_b)

    # Using ^ operator
    symmetric_difference_operator_result = set_a ^ set_b

    print(symmetric_difference_result)
    print(symmetric_difference_operator_result)

2.5 In-Place Operations.

Python offers in-place counterparts for set operations, allowing you to replace the contents of a set with the result directly.

def set_in_place_operation():

    set_a = {1, 2, 3, 4, 5}
    set_b = {3, 4, 5, 6, 7, 8}

    c = set_a.copy()
    c |= set_b # In-place union
    print(c) 

    d = set_a.copy()
    d &= set_b # In-place intersection
    print(d)

2.6 Set Comparison.

You can check if a set is a subset or superset of another set and determine set equality.

def set_comparison():

    a_set = {1, 2, 3, 4, 5}

    print({1, 2, 3}.issubset(a_set)) # Output: True
    
    print(a_set.issuperset({1, 2, 3})) # Output: True

    print({1, 2, 3} == {3, 2, 1}) # Output: True

3. Conclusion.

Sets offer efficient and powerful tools for managing unique collections of data in Python. Understanding their operations and behaviors will greatly enhance your ability to work with various datasets and perform set-related computations effectively.

4. Demo Video for This Article.

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.