Suresh Jeevanandam wrote: > In python all numbers are immutable.
True. > This means there is one object ( > a region in the memory ) created every time we do an numeric > operation. False. Memory regions can be pooled in a way that "allocation" is a O(1) operation. > I hope there should have been some good reasons why it was > designed this way. Yes, so that you can obtain a pass-by-value semantic for numeric types. That is, if you pass a number to a function, it can't modify it. You consistenly use "a = foo(a)" to do a calculation on "a", instead of having half programs doing "foo(a)" and the other half doing "a = foo(a)". Also, it's done so that you don't need to special case integer literals: they are (fixed) names to the same immutable instances and nobody can modify the value of 13 or any other literal. > But why not have mutable numbers also in the language. A type which > would behave as follows: > > a = MutableInt(12) > b = a > > Now both a and b should refer to the same memory location. Any change > in the object should get reflected in all the references. > > a.assign(13) # Same memory location should be updated with value 13, b > is also 13 now. > > Now we can further optimize: > > a.incrementOne() # equivalent to a++ in C++ > a.decrementOne() > > and the augmented assignment operation also could be made optimized. So you just created a numeric type which does not work with normal operators. This is so unpythonic. I don't think anybody wants to write "incrementOne" when "+ 1" exists and does the same it used to do in primary school. Even if you overloaded all the operators, you still wouldn't be able to use '=' to do assignment, which pretty much makes your class useless or very unpythonic to use (= wrong). > In any application most of the operation is numerical. So, i think, we > should get a good speed advantage with the availability of mutable > numbers. What do you think ? You are doing premature optimization. It's so premature that it's even a brain thing. You *presume* Python to be slow, you *presume* that this presumed slowness comes from numbers being immutables. But you didn't *measure* it, you didn't try it on a real-world case. You didn't even look at the Python source code to check if your assumptions were true. Try to check your assumptions before designing solutions to problems which do not exist. I suggest you start writing real-world Python before doing so many assumptions. -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list