On 01/-10/-28163 02:59 PM, Francesco Loffredo wrote:
On 03/12/2010 1.32, Steven D'Aprano wrote:
<snip>
mylist = [x for x in mylist if x != "something"]
Up to this point, I share experiences and solution. But the next point
did thrill me:
If you really need to modify the list in place, and not just re-bind
the name "mylist" to the new list, then one tiny change will do
it:
mylist[:] = [x for x in mylist if x != "something"]
I thought mylist[:] was a copy of mylist, and the two lines above would
generate exactly the same code!
Is this a special optimization by the Python interpreter, or is it just
a mistake in my understanding of the slice operator?
Not an optimization, but a fundamental part of the language.
On the left side of an assignment, a slice operator specifies which part
of an existing object gets replaced by the right side. So whenever you
have a list that's referred to by more than one symbol, you may want to
use a syntax like this.
The slice operator does a very different thing inside an expression (eg.
on the right side of an assignment).
DaveA
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor