Background
Suppose I have 2 global variables a = [1,2,3] and b = ['a','b'], If I must exchange a and b inside a function, I can do with following code:
a = [1,2,3]
b = ['a','b']
def fun1():
global a,b
temp = a[::-1]
a = b[::-1]
b = temp
fun1()
print(a,b)
Out:
['b', 'a'] [3, 2, 1]
However, If a and b are parameters of my function, how do we do it?
a = [1,2,3]
b = ['a','b']
def fun2(a,b):
global a,b
temp = a[::-1]
a = b[::-1]
b = temp
fun2(a,b)
print(a,b)
Raise Error:
SyntaxError: name 'a' is parameter and global
My attempt
I tried to do with exec, it works on Python 3.7, However, it does not work on Codewars 3.6 env. I don't know the reason, maybe I just find wrong method.
a = [1,2,3]
b = ['a','b']
def exchange_with(a, b):
temp = a[::-1].copy()
exec('a = b[::-1]',globals())
exec('b = temp',locals(),globals())
exchange_with(a, b)
a,b
Out:
(['b', 'a'], [3, 2, 1])