No built-in swap function?

Tim Peters tim.one at comcast.net
Mon Mar 29 12:40:51 EST 2004


[Andrew Koenig]
> 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.

That's right.

> Is there anything better than
>
>     v[i], v[j] = v[j], v[i]

Not in general, no.

> (which I don't like particularly because it evaluates each of v[i]
> and v[j] twice)?

Well, it evaluates "i" and "j" twice each, and evaluates "v" four times.
The LHS in general creates calls to v.__setitem__, though, while the RHS
creates calls to v.__getitem__, so there's nothing more to be saved here in
general.  The CPython eval loop happens to special-case the snot out of the
RHS v[whatever] thingies when v is a list, and whatever is an int, doing it
all inline.

In all CPythons released to date, you'll probably find that

    temp = v[i]
    v[i] = v[j]
    v[j] = temp

runs faster than

    v[i], v[j] = v[j], v[i]

but that's an implementation accident that may get cured in Python 2.4 (it
has to do with the exact sequence of bytecodes generated, and the latter way
currently burns time building then tearing apart an intermediate 2-tuple).





More information about the Python-list mailing list