I want to pass n variables to a function in python and have the function sanitize these variables. My first attempt at this was
list_of_variables = [a, b, c,]
def sanitize(*args):
for arg in args:
arg = str(arg) #example
sanitize(*list_of_variables)
but arg becomes a local variable and the original array remains unaffected.
Attempt#2
for arg in args:
global arg
but this didnt work since arg is assigned before global declaration. putting global arg above the loop also didnt work.
is there a way to make this function perform a certain action over n variables.
if you put your var(s) in a list, there is no need to use indirection, just read the list in sanitize :
a=10
b= 12/3
c= "ABCDEF"
list_of_variables = [a, b, c]
def sanitize(aList):
for i in range (0, len(aList)):
aList[i] = str(aList[i])
sanitize(list_of_variables)
print(list_of_variables)
result : ['10', '4.0', 'ABCDEF']
But this will not work with sanitize(a,b,c)
as python creates a tuple, not a list and a tuple cannot be modified;
if you want to use sanitize with a free list of var(s), you must return something else than the initial tuple. A code could be :
def sanitize(*args):
aList=[]
for arg in args:
aList.append(str(arg))
return aList
result = sanitize(a,b,c)
print(result)
You get : ['10', '4.0', 'ABCDEF']
But take care that in any case of these examples, a, b or c stay unchanged.
print (a,b,c)
will always give 10 4.0 ABCDEF
You are not manipulating pointers as it could be in C !
HTH