0

Is it possible to create a pointer in Python to make a variable equal to a string after that string is changed elsewhere? Something like this below concept:

a = 'hello'
b = a
a = 'bye'

print(b) # is it possible have b be 'bye' without simply doing b = a again?
Danlo9
  • 133
  • 3
  • 12
  • 5
    You're not actually changing the string. Read up on [the relationship between objects and variables in Python](https://nedbatchelder.com/text/names.html) - it'll clear up a lot of misunderstandings, and make it clearer what's possible and why. – user2357112 Aug 25 '20 at 22:26
  • 2
    This would be possible by having a mutable container like a list hold the object, then doing a mutating operation on the list. It wouldn't be possible as simply as you have here though. – Carcigenicate Aug 25 '20 at 22:31
  • Out of curiosity, if this were in C and the variables were char* , would this be the expected behavior because a and b would be pointing to the same place in memory? – Danlo9 Aug 25 '20 at 22:49
  • Does this answer your question? [how to re-assign variable in python without changing id?](https://stackoverflow.com/questions/51336185/how-to-re-assign-variable-in-python-without-changing-id) – Gino Mempin Aug 25 '20 at 23:14
  • 1
    This would have the same behavior in C. If `b` is made to be a pointer to the same memory as `a`, reassigning `a` afterwards wouldn't have any effect on `b`. Also similar to here, you would need a second level of "nesting" for this to work. If in C you had `char**` pointers, you could reassign the first level of pointers, and the change would be reflected in `b`. – Carcigenicate Aug 25 '20 at 23:24

1 Answers1

4

As pointed out in the comments (and the link it points to), you initially have a and b both pointing to the string 'hello', but re-assigning a does not affect b, which will still point to the string 'hello'.

One way to achieve what you want is to use a more complex object as a container for the string, e.g. a dictionary:

a = {'text': 'hello'}
b = a
a['text'] = 'bye'
print(b['text']) # prints 'bye'
Anis R.
  • 6,656
  • 2
  • 15
  • 37