[Tutor] permutations?

Dave Angel davea at ieee.org
Tue Dec 14 14:56:05 CET 2010

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).


More information about the Tutor mailing list