No built-in swap function?

John J. Lee jjl at pobox.com
Mon Mar 29 19:46:47 CEST 2004


"Andrew Koenig" <ark at acm.org> writes:

> I am looking for the most effective way to exchange v[i] and v[j], and
> expected to find something like
> 
>     v.swap(i, j)
> 
> but it doesn't seem to exist.  Is there anything better than
> 
>     v[i], v[j] = v[j], v[i]
> 
> (which I don't like particularly because it evaluates each of v[i] and v[j]
> twice)?

I don't think so.

It seems an odd question in one way: Saying that it evaluates v[i] and
v[j] twice may be true, but ignores the fact that v[a] is quite
different from v[a] = b -- one does a lookup (whether it be a dict
lookup, list indexing operation, or whatever), and the other is an
assignment (whether setting a dict key/val pair, setting a list item,
etc).

I admit I don't like the repetition of v[i] and v[j], though of course
that can be solved by writing a function.  I suppose a function is
best here, not a method, because you might want to apply it to any
sequence.

I-am-not-a-language-lawyer-ly y'rs,


John



More information about the Python-list mailing list