On Jul 7, 10:04 pm, kj <no.em...@please.post> wrote: > I'm having a hard time coming up with a reasonable way to explain > certain things to programming novices. > > Consider the following interaction sequence: > > >>> def eggs(some_int, some_list, some_tuple): > > ... some_int += 2 > ... some_list += [2] > ... some_tuple += (2,) > ... > > >>> x = 42 > >>> y = (42,) > >>> z = [42] > >>> eggs(x, y, z) > >>> x > 42 > >>> y > (42,) > >>> z > [42, 2] > > How do I explain to rank beginners (no programming experience at > all) why x and y remain unchanged above, but not z? > > Or consider this one: > > >>> ham = [1, 2, 3, 4] > >>> spam = (ham,) > >>> spam > ([1, 2, 3, 4],) > >>> spam[0] is ham > True > >>> spam[0] += [5] > > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: 'tuple' object does not support item assignment>>> ham += [5] > >>> spam > > ([1, 2, 3, 4, 5, 5],) > > > > What do you say to that? > > I can come up with much mumbling about pointers and stacks and > heaps and much hand-waving about the underlying this-and-that, but > nothing that sounds even remotely illuminating. > > Your suggestions would be much appreciated! > > TIA! > > kj
I would go with something like this: """ In object oriented programming, the same function or operator can be used to represent different things. This is called overloading. To understand what the operator/function do, we have to look at the kind of object it is applied to. In this case, the operator "+=" means two different things: - for strings and numbers it means : "create a new object by merging the two operands". This is why the original object is left the same. - for lists, it means : "increase the left operand with the contents of the right operand". This is why the original object is changed """ You couuld also add: """ You see, in python everithing is an object. Some object can be changed (mutable objects), others cannot. """ but this is another story. P:S : Sometime I think they should not have allowed += on immutables and forced everybody to write s = s + "some more". Ciao ---- FB -- http://mail.python.org/mailman/listinfo/python-list