tough-to-explain Python

Chris Rebert clp2 at rebertia.com
Tue Jul 7 16:08:50 EDT 2009


On Tue, Jul 7, 2009 at 1:04 PM, kj<no.email at 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!

You might find the following helpful (partially):
http://effbot.org/zone/call-by-object.htm

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list