tough-to-explain Python

kj no.email at please.post
Tue Jul 7 22:04:46 CEST 2009



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



More information about the Python-list mailing list