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?
2 Answers
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
1 Comment
Rahul K P
Yeah, this is a much better approach.
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
1 Comment
juanpa.arrivillaga
this only ever works in the global scope, though
y = xwould add a reference to the object inx.del xwould deletex, reducing the reference.