0

The following code (python3) prints 5 and not 4.

x = 5
y = x
x = 4
print(y)

But every now and I find a situation where the opposite behavior occurs, where a variable is assigned to some location in memory rather than the value stored there. A few times I have found a bug in my code because of something like this.

Is there a similar situation to the above code (and in Python), in which a beginner might intend for the code to store the current value of one variable in a new variable, but instead of the value it assigns the identifier? Also, I don't mean to impose any specific data type by the words "value" and "variable" here, so my apologies if these terms are not correct.

If there are some comments about how this behavior varies over some common languages (esp. python, javascript, java, c, haskell), I would be interested to hear about that. And of course, any suggestions on what is appropriate terminology for this question (and how to tag it) would be kindly appreciated as well.


EDIT: I'm accepting an answer which describes how the behavior varies with immutable/mutable types as this is likely the behavior I had encountered, and I had asked in particular about a source of confusion for a beginner programmer. However, someone visiting this page with a similar question should refer also to the comments section which indicates that a general answer isn't as simple as mutable/immutable data types.

7
  • 6
    This question is too broad to be answered here but search for "mutable and immutable types" for starters. Commented Feb 1, 2019 at 3:32
  • @Selcuk Thank you very much. I appreciate your comment, and I should be able to figure this out on my own at this point. I understand there may be too many "similar situations" to give a specific answer to the question. But is the answer not simply: "if its a mutable type then one behavior happens, if its immutable then the other behavior happens" perhaps followed by a short list of common immutable/mutable types in python? Commented Feb 1, 2019 at 3:48
  • 1
    @Ben It is not that simple as there are many intricacies such as copy/deepcopy operations and nested structures. Also when you do x = something you always create a new reference, even if that something is of a mutable type. It is better to read a few introductory articles then experiment yourself. Commented Feb 1, 2019 at 3:52
  • 2
    Ned Batchelder's article is one of the best starter resources on this topic. Commented Feb 1, 2019 at 4:13
  • 1
    @Selcuk Thanks again, your comments have helped me find the information I was looking for. Perhaps my question should have been along the lines of: "what is the terminology I need to know to read further about this". I'll do my best to be mindful of asking appropriate questions in the future. Commented Feb 1, 2019 at 4:27

3 Answers 3

2
>>> 1
1
>>> id(1)
140413541333480
>>> x = 1
>>> id(x)
140413541333480
>>> z = 1
>>> id(z)
140413541333480
>>> y = x
>>> id(y)
140413541333480
>>>

For the purpose of optimisation, there's only single copy of 1 and all variables are referencing to it.

Now, integers and strings, in python, are immutable. Every time you define a new one, a new reference/id gets generated.

>>> x = 1 # x points to reference (id) of 1
>>> y = x # now y points to reference (id) of 1
>>> x = 5 # x now points to a new reference: id(5)
>>> y     # y still points to the reference of 1
1
>>> x = "foo" 
>>> y = x
>>> x = "bar"
>>> y
'foo'
>>> 

Lists, dicts are mutable, i.e., you can modify the value at the same reference.

>>> x = [1, 'foo']
>>> id(x)
4493994032
>>> x.append('bar')
>>> x
[1, 'foo', 'bar']
>>> id(x)
4493994032
>>>

So, if your variable is pointing to a reference and the reference contains an mutable value and the value is updated, the variable will reflect the latest value.

If the reference is overridden, it'll point to whatever the reference is pointing to.

>>> x = [1, 'foo']
>>> y = x  # y points to reference of [1, 'foo'] 
>>> x = [1, 'foo', 'bar'] # reference is overridden. x points to reference of [1, 'foo', 'bar']. This is a new reference. In memory, we now have [1, 'foo'] and [1, 'foo', 'bar'] at two different locations. 
>>> y
[1, 'foo']
>>>

>>> x = [1, 'foo']
>>> y = x
>>> x.append(10) # reference is updated
>>> y
[1, 'foo', 10]
>>> x = {'foo': 10}
>>> y = x
>>> x = {'foo': 20, 'bar': 20}
>>> y
{'foo': 10}
>>> x = {'foo': 10}
>>> y = x
>>> x['bar'] = 20 # reference is updated
>>> y
{'foo': 10, 'bar': 20}
>>>

The 2nd part of your questions (common languages) is too broad and Stackoverflow isn't the right forum for that. Please do your research on your languages of interest - there's plenty of information available on each language group and it's forums.

Sign up to request clarification or add additional context in comments.

2 Comments

This was quite a helpful elaboration on one of the comments I received above (both with regard to the question, and the aspect regarding the issue of being off-topic due to too much breadth) so thank you very much on both counts.
Glad it helped :)
0

Your solution is in this video...From this video, you can understand it properly. so please watch it carefully...

https://www.youtube.com/watch?v=_AEJHKGk9ns

unlike other languages, python does not make a copy of the object and assign it to new variable i.e. in your case y=x

What actually python does here is points the reference of y to the value object that was stored in x

let's get it more clear with your example

x=5

after execution of this line, x will be referencing to an object in memory which stores value 5

y = x

now, x and y both will be referencing to the value 5.

x=4

The magic of python starts on this line, keep in mind that here x and y are immutable objects which means their values can not be changed but when you assign 4 to x it simply creates a new block in memory containing 4 and x will now reference to that block, however, y is still referencing the old block which has value 5. so output will be 5

in case of a mutable object like a list if you do this

x = [5, 6]
y = x
x.append(7)
print(y)

This will print

[5, 6, 7]

as output

3 Comments

Thanks for contributing, but videos aren't searchable. SO likes text answers that can be indexed by Google and other search engines. Can you summarize that video for us?
Thank you for your request, I have updated my answer as you mentioned. Happy coding.
@KirkStrauser Please check it out :)
0
x = 5   
id(x) = 94516543976904     // Here it will create a new object

y = x    
id(y) = 94516543976904    // Here it will not create a new object instead it will refer to x (because both of them have same values).

x = 4
id(x) = 94516543976928    // Here we are changing the value of x. A new object will be created because integer are immutable.

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.