Hacker News new | past | comments | ask | show | jobs | submit login

> 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.




> The difference is that Python guarantees that integers are immutable.

Python's guarantees can be worked around: https://gist.github.com/Jach/1208215


Arguably, 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)


You 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.


OP 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.


His 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.


That's why understanding when variable assignment gives you a reference vs. a copy is absolutely crucial to working with object-oriented languages.


Right, I was talking specifically about the integer case in Python


It 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




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: