[Python-ideas] add a list.swap() method

Kristján Valur Jónsson kristjan at ccpgames.com
Thu Jun 25 21:52:25 CEST 2009

> -----Original Message-----
> From: python-ideas-bounces+kristjan=ccpgames.com at python.org
> [mailto:python-ideas-bounces+kristjan=ccpgames.com at python.org] On
> Behalf Of Terry Reedy
> Sent: 25. júní 2009 17:58
> To: python-ideas at python.org
> Subject: Re: [Python-ideas] add a list.swap() method
> Kristján Valur Jónsson wrote:
> >
> >> -----Original Message-----
> >
> > The idea is for example to speed up the initialization of lists (and
> > subclasses of lists) from other lists when the source list's contents
> > is to be discarded.
> Which is why 'swap' is confusing.  You want to swap list-body pointers,
> which is meaningless in Python itself. Nick's 'fromlist' is better. It
> describes the effect without reference to the backstage magic.

It is only one application, the other is a fast implementation of 
a[:], b[:] = b[:], a[:]

There is precedence, I think.
list.reverse() is semantically identical to 
list[:] = reversed(list)

but it doesn't invoke any magic methods, and it relies on "backstage magic" to do its work in the most efficient way.
Same goes for sort(), really.

The difference with swap(), is that it will also magically affect an operand list.  But I think that both reverse() and sort() can be dangerous to list subclasses with class invariants.

I think there are other cases.  list.pop() doesn't appear to invoke any magic methods either, and so must be a killer for list invariants.


More information about the Python-ideas mailing list