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 set\n")
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 set\n")
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 set\n"))
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
CodePudding user response:
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?