(Apr-20-2017, 05:38 AM)dave925 Wrote: How do I make variables within variables modifiable?
y = '1' x = 'hello'+y y = '2'If I print <x>, it will only give me 'hello1' not 'hello2'.
Is there an easy way to make <y> modifiable within <x>?
You are confusing string concatenation with list copy modification
When you do something like
x = [1, 2] y = x x[0] = 2then
y[0]
will become 2 too, because both x
and y
point to the same list in memory. Assignment in Python does create a new alias (reference, pointer) to right hand operator.With
x = 'hello'+y
you create a new temporary string object than ends with value of the string in y
and creates reference x
to that object; that new object does not contain reference to y
Of course, you can always try to override string object to simulate that behavior
Test everything in a Python shell (iPython, Azure Notebook, etc.)
- Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
- Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
- You posted a claim that something you did not test works? Be prepared to eat your hat.