On 24 April 2013 20:07, Alan Gauld <alan.ga...@btinternet.com> wrote: > On 24/04/13 16:52, Dave Angel wrote: > >>> Does it mean? ; totalViruses[i] = totalViruses[i]/float(numTrials) >>> >> As the others have said, that's exactly right, at least if >> totalViruses[i] is immutable, like an int or a float. > > > What difference does immutability make here? > Even if totalViruses[i] is mutable (an object > or another mutable type) it would still work > provided it supported the division operator > for floats. Or am I missing something?
Yes. >> It's a subtle distinction, but for now, just remember that it's true for >> "numbers", but that somebody might redefine one of these operators for >> other object types. They could not do that for numbers, however. > > Surely you could redefine it for a subclass of numbers too? > Or, again, am I missing something? You can redefine it for numbers but it's just not typically done that way in Python. The subtle distinction that Dave is referring to is about modifying an object in place vs rebinding a name to a newly created object. For immutable objects a+=b will create a new object, the result of a+b and bind that new object to the name a. For mutable objects a+=b typically modifies the object a in place so that other references to the object will also see the change. Consider the following program: def append_zeros(list1, list2): list1 = list1 + [0, 0, 0] list2 += [0, 0, 0] print(list1) print(list2) outerlist1 = [1, 2, 3] outerlist2 = [1, 2, 3] append_zeros(outerlist1, outerlist2) print(outerlist1) print(outerlist2) The output is: [1, 2, 3, 0, 0, 0] [1, 2, 3, 0, 0, 0] [1, 2, 3] [1, 2, 3, 0, 0, 0] Which behaviour occurs is entirely up to the author of the __iadd__ method of the class in question. This method can modify and return self or it can return a different object. Oscar _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor