Global Set in Python

In Python, a set is a collection of unique elements. A global set is a set that is defined outside of any function or class and can be accessed from anywhere in the program.

Here is an example of how to define and use a global set in Python:

# Define a global set
my_set = set()

# Add elements to the set
my_set.add(1)
my_set.add(2)
my_set.add(3)

# Print the set
print(my_set) # Output: {1, 2, 3}

# Define a function that uses the global set
def add_to_set(num):
    global my_set
    my_set.add(num)

# Call the function to add an element to the set
add_to_set(4)

# Print the updated set
print(my_set) # Output: {1, 2, 3, 4}

In this example, we first define a global set named my_set using the set() function. We then add elements to the set using the add() method.

We then define a function named add_to_set that takes a number as a parameter and adds it to the global set using the add() method. Notice that we have to use the global keyword inside the function to let Python know that we are referring to the global set and not creating a new local variable.

Finally, we call the add_to_set() function with the parameter 4 to add that element to the global set, and then print the updated set using the print() function.

As you can see, a global set can be modified from within a function using the global keyword, and its updated contents can be accessed from anywhere in the program.

Leave a Reply