1

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?
5
  • 5
    You're not actually changing the string. Read up on the relationship between objects and variables in Python - it'll clear up a lot of misunderstandings, and make it clearer what's possible and why. Commented Aug 25, 2020 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. Commented Aug 25, 2020 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? Commented Aug 25, 2020 at 22:49
  • Does this answer your question? how to re-assign variable in python without changing id? Commented Aug 25, 2020 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. Commented Aug 25, 2020 at 23:24

1 Answer 1

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

Comments

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.