list.clear() missing?!?

Ben C spamspam at spam.eggs
Fri Apr 14 08:05:24 EDT 2006


On 2006-04-14, Sergei Organov <osv at javad.com> wrote:
> Dennis Lee Bieber <wlfraed at ix.netcom.com> writes:
>> 	It always means bind... But if the LHS is a mutable object, AND you
>> have specified a component of that object, it is the component that is
>> being rebound...
>>
>> 	lst[:] = [] 

>> [...]

> Me gets corrected, thanks. Now I need to unroll my mind somewhat back to
> figure out when and why I started to believe it sometimes assigns ;)

I used to think it assigned with things like integers, because if you
write:

    a = 5
    b = a
    b += 1
    print a

a is still 5. So it looked like a and b stored values and b got a "copy"
of a's value. But this is the wrong interpretation,

    b += 1

is really b = b + 1, and rebinds b.

You can see what's really going on if you use the id() function on a and
b during these operations.

The other reason for the confusion is that I think in Java a variable
either stores a value, in the case of numbers, or a reference in the
case of objects (or a copy-on-write reference, which behaves like a
value, in the case of strings). In Python it's better to think of it as
always a reference, and to think in terms of immutable vs. mutable
objects that are referred to.

If it weren't for the id() function I think the difference between
"variable stores value", "variable stores immutable reference" and
"variable stores copy-on-write reference" would be implementation detail
and never visible to the programmer. That's why it's easy to be
"confused"-- most of the time these interpretations are equivalent, so
it doesn't matter which you work with.



More information about the Python-list mailing list