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?

scissors127
  • 21
  • 1
  • 6
  • 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. – blurfus Oct 24 '22 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? – IMSoP Oct 24 '22 at 21:56
  • @blurfus I am just curious if it is possible. – scissors127 Oct 24 '22 at 21:57
  • `y = x` would add a reference to the object in `x`. `del x` would delete `x`, reducing the reference. – tdelaney Oct 24 '22 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. – tdelaney Oct 24 '22 at 22:04
  • Take a look at this https://stackoverflow.com/questions/1396668/get-object-by-id – learner Oct 24 '22 at 22:04
  • In Python, variables *are names* that refer to objects. You have a string object being referred to by the variable (name) `x`. If you want to assign that string to the variable (name) `y`, simply do `y = x`. – juanpa.arrivillaga Oct 24 '22 at 22:13

2 Answers2

3

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
sj95126
  • 6,520
  • 2
  • 15
  • 34
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
 
Rahul K P
  • 15,740
  • 4
  • 35
  • 52