tough-to-explain Python
Piet van Oostrum
piet at cs.uu.nl
Tue Jul 7 16:53:13 EDT 2009
>>>>> kj <no.email at please.post> (k) wrote:
>k> I'm having a hard time coming up with a reasonable way to explain
>k> certain things to programming novices.
>k> Consider the following interaction sequence:
>>>>> def eggs(some_int, some_list, some_tuple):
>k> ... some_int += 2
>k> ... some_list += [2]
>k> ... some_tuple += (2,)
>k> ...
>>>>> x = 42
>>>>> y = (42,)
>>>>> z = [42]
>>>>> eggs(x, y, z)
>>>>> x
>k> 42
>>>>> y
>k> (42,)
>>>>> z
>k> [42, 2]
>>>>>
>k> How do I explain to rank beginners (no programming experience at
>k> all) why x and y remain unchanged above, but not z?
You shouldn't. That's not for beginners. Leave it waiing until you get
to the advanced level.
>k> Or consider this one:
>>>>> ham = [1, 2, 3, 4]
>>>>> spam = (ham,)
>>>>> spam
>k> ([1, 2, 3, 4],)
>>>>> spam[0] is ham
>k> True
>>>>> spam[0] += [5]
>k> Traceback (most recent call last):
>k> File "<stdin>", line 1, in <module>
>k> TypeError: 'tuple' object does not support item assignment
>>>>> ham += [5]
>>>>> spam
>k> ([1, 2, 3, 4, 5, 5],)
>>>>>
>k> What do you say to that?
Mutable and immutable. But use different examples. Like
ham = [1, 2, 3, 4]
spam = (1, 2, 3, 4)
spam[0] += 1 will give the same error message. You can't change the
components of a tuple.
Your example above is similar. The spam[0] += [5] appends the 5 to the
list in spam[0] (so it appends to ham), and then tries to assign the
result of it to spam[0], which is not allowed. That the item it tries to
assign is the same as the item that was already there doesn't matter.
So dont't forget += is a real assignment, even when it is an in-place
modification. Your example just proves that. The language ref manual
says:
With the exception of assigning to tuples and multiple targets in a
single statement, the assignment done by augmented assignment
statements is handled the same way as normal assignments.
But I think that your example isn't for beginners either.
--
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org
More information about the Python-list
mailing list