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

Aahz aahz at pythoncraft.com
Thu Jun 25 15:47:00 CEST 2009

On Thu, Jun 25, 2009, Kristj?n Valur J?nsson wrote:
> From: alex23
>> Kristj?n Valur J?nsson <krist... at ccpgames.com> wrote:
>>> The idea is to speed up the swapping of list elemenst so that
>>> a.swap(b)
>>> is equivalent to
>>> a[:], b[:] = b[:], a[:]
>>> but without all the overhead of creating slices, assigning them and
>>> so forth.
>> I think I'd use a mapping to hold the lists so I could do a straight
>> re-assignment:
>>  d['a'], d['b'] = d['b'], d['a']
> This is roughly equivalent to
> a, b =  b, a
> right?

Yes and no.  The point is that anyone holding a reference to ``d`` will
see the changes to d['a'] and d['b'] (this would also apply to using an
instance to proxy the changes through attributes).  It's the usual trick
for handling wholesale updates to mutable objects.  Therefore it doesn't
have the problem of the plain tuple-swap of losing the references.  For
any use-case that really is swapping as opposed to the fast
initialization that you want, alex23's idea is a good kludge, which
limits the scope of usefulness for what you want.
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha

More information about the Python-ideas mailing list