No swap function in Python?
Skip Montanaro
skip at pobox.com
Wed May 30 12:00:39 EDT 2001
>> Finally, if the behaviour is guaranteed, is this an efficient way of
>> doing a swap?
Thomas> Yes.
Relatively speaking, yes it is efficient. Still, you do wind up creating
and deleting a tuple as a result, which while not terribly expensive is not
without cost. "(a,b) = (b,a)" compiles to (approximately):
LOAD_FAST b
LOAD_FAST a
BUILD_TUPLE 2
UNPACK_TUPLE 2
STORE_FAST a
STORE_FAST b
It's easy to see how you can use the runtime stack without going through the
BUILD/UNPACK pair:
LOAD_FAST b
LOAD_FAST a
STORE_FAST b
STORE_FAST a
Any peephole optimizer can do this for you... ;-)
Skip
More information about the Python-list
mailing list