Can I change my variable name in Python? For example, I have a string x
, and I want to change string x
variable name to y
, how can I do it?
CodePudding user response:
Python variables are references to objects, so you can simply create a second name pointing to the existing object and delete the old name:
y = x
del x
CodePudding user response:
Ideally, the good approach will be renaming the variable, like y = x
But you can do this in weird approach with using globals()
In [1]: x = 10
In [2]: globals()['y'] = globals().pop('x')
In [3]: 'x' in globals()
Out[4]: False
In [4]: 'y' in globals()
Out[4]: True