No built-in swap function?

Andrew Koenig ark at acm.org
Mon Mar 29 12:54:37 EST 2004


"John J. Lee" <jjl at pobox.com> wrote in message
news:ad1zeebc.fsf at pobox.com...

> 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).

Of course.  Nevertheless there are some operations in common, especially if
you're trying to do something like

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

> 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.

Perhaps.  Obviously, I can write

    def swap(v, i, j):
        v[i], v[j] = v[j], v[i]

and then my example above becomes

    swap(v, i, i+j)

However, if swap were a builtin, I think I'd expect it to be a method
because that way, it would be easier for the function to depend on the type
of v.

Anyway, it's no big deal; I just want to be sure I wasn't missing something
that's already there.





More information about the Python-list mailing list