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.
CodePudding user response:
You can reassign members of a list like this:
def sanitize(args):
for index,arg in enumerate(args):
args[index] = str(arg) #example
list_of_variables = [a, b, c,]
sanitize(list_of_variables)
CodePudding user response:
You can return the sanitised variables back from the function to the caller. Besides, since you're passing the list to the function when you call it, you don't need the non-keyword variables *kwargs
, since lists are perfectly good variables that can serve as arguments for a function:
list_of_variables = [a, b, c]
def sanitize(*args):
l = []
for arg in args:
l.append(str(arg))
return l
list_of_variables = sanitize(list_of_variables)