1

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?

7
  • As far as I can tell, no, you cannot do that. However, why would you want to do this? Nothing is preventing you from having a second variable with the other name you seek. Commented Oct 24, 2022 at 21:55
  • 2
    Generally, a variable is thought of as a way to associate a name to a value, so it's not clear what "changing the name" would mean, other than associating a new name (i.e. a new variable) with the same value. Can you expand on what you're trying to achieve? Commented Oct 24, 2022 at 21:56
  • @blurfus I am just curious if it is possible. Commented Oct 24, 2022 at 21:57
  • y = x would add a reference to the object in x. del x would delete x, reducing the reference. Commented Oct 24, 2022 at 21:57
  • Variables are usually key/value pairs in a dictionary - function local variables being a notable exception. Schemes that add a new key to the dictionary and then delete the old name exist, but fundamentally you can't just change the key itself. Keys are hashable objects and string keys are immutable, so no changing of the key object itself. Commented Oct 24, 2022 at 22:04

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, this is a much better approach.
1

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

this only ever works in the global scope, though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.