Can I change variable name in Python

4.1k Views Asked by At

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

There are 2 best solutions below

1
sj95126 On

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
Rahul K P On

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