3 ms·
> If you've used Java or Python, you'll probably be familiar with the idea that some types of data behave differently from others when you assign them from one
by michaelhoffman 13y ago
> If you've used Java or Python, you'll probably be familiar with the idea that some types of data behave differently from others when you assign them from one variable to another. If you write an assignment such as ‘a = b’ where a and b are integers, then you get two independent copies of the same integer: after the assignment, modifying a does not also cause b to change its value.
This is incorrect when it comes to Python. a and b will be two different names for the same integer object, which is stored in a single memory location. The difference is that Python guarantees that integers are immutable.
- jffry 13y agoArguably, to a user of the language, these are imperceptible from independent. Changing one cannot change the other (except perhaps through some exotic double-underscore-prefixed function with which my vague knowledge of Python is unfamiliar)
- jpace121 13y agoYou definitely notice the difference when dealing with mutable types in python, like lists. >> a = [1,2,3] >> b = a >> a.append(4) >> b #[1,2,3,4] This is one of the things that throws off many beginners, and is an easy trap to fall into, not exotic at all.
- beambot 13y agoOP literally says this in the next sentence: > But if a and b are both variables of the same Java class type, or Python lists, then after the assignment they refer to the same underlying object, so that if you make a change to a (e.g. by calling a class method on it, or appending an item to the list) then you see the same difference when you look at b.
- rcxdude 13y agoHis point is that there isn't a difference in python: in both cases you're just changing labels, but in the case of integers they're pointing to immutable objects.
- jffry 13y agoRight, I was talking specifically about the integer case in Python
- kyllo 13y agoThat's why understanding when variable assignment gives you a reference vs. a copy is absolutely crucial to working with object-oriented languages.
- Jach 13y ago> The difference is that Python guarantees that integers are immutable. Python's guarantees can be worked around: https://gist.github.com/Jach/1208215 https://gist.github.com/Jach/1208215
- hornetblack 13y agoIt is possible to do some evil hackery and change the value of integers in the small number cache. http://hforsten.com/redefining-the-number-2-in-python.html http://hforsten.com/redefining-the-number-2-in-python.html