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

Josiah Carlson josiah.carlson at gmail.com
Thu Jun 25 23:14:34 CEST 2009


-1

I've done some pretty shady things with Python over the years, but
swapping the contents of two lists (or list subclasses) isn't one.
That this can be implemented in a properly formatted 2-line function
(modulo your function naming style):

def SwapLists(a, b):
    a[:], b[:] = b[:], a[:]

... necessarily requires me to invoke "not all x line functions should
be built-in (or methods)".

As for using list.sort(), list.reverse(), or even list.pop() as
examples of why list.swap() should exist, that doesn't fly.  Sorting,
reversing, and popping are *very* common operations in Python code.
Swapping list contents? ...not so common.

If you're really swapping contents that often, you may want to
consider a different design with a better algorithm (swap 2 pointers
rather than n+m), rather than speeding up the slow algorithm.

 - Josiah

2009/6/25 Kristján Valur Jónsson <kristjan at ccpgames.com>:
>> -----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.
>
> K
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



More information about the Python-ideas mailing list