My sets is not being updated after I do operations in a fucntion

Question:

I have 2 defined sets they are

set1 = {1, 2, 3}
set2 = {1, 3, 4, 6}

and I have 2 fucntions. One for add a value to sets and one for print it

def printSet():
    x = input("Enter name of the setn")
    if x in globals():
        anySet = set(globals()[x])
        result = print("Your set is:n", anySet)
    else:
        result = print("ERROR")
    return result


def addSet():
    x = input("Enter name of the setn")
    if x in globals():
        anySet = set(globals()[x])
        print("Your set is:n", anySet)
        y = int(input("Enter the value that you want to add to the setn"))
        anySet.add(y)
        result = print("Your new set is:n", anySet)
    else:
        result = print("ERROR")
    return result

Let’s say i add the value "4" to the set1. When I print it in the fucntion the answer is

Your new set is:
 {1, 2, 3, 4}

That is okey but after the line I execute addSet fucntion, if I try to print set1 with

print(set1)

set1 is not being updated and the output is

 {1, 2, 3}

How can I fix this problem

Asked By: Key_Master

||

Answers:

Your code would work, if it weren’t for the copy you are creating with anySet = set(globals()[x])

Simply use anySet = globals()[x]

Example:

set1 = {1, 2, 3}
def modify():
    anyset = set(globals()['set1']) # creates a copy
    anyset.add(4)
    print(set1) # {1, 2, 3}
modify()

W/O creating a copy:

set1 = {1, 2, 3}
def modify():
    anyset = globals()['set1']
    anyset.add(4)
    print(set1) # {1, 2, 3, 4}
modify()

Side note: using globals() is usually considered bad practice, maybe you could create your own global dict that references your variables by name. related issue: How do I create variable variables?

Answered By: Mike Scotty
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.