Python Tip: Swapping Two Objects


nathanieltroutman - Posted on 08 October 2008

So I wanted to swap to objects, and I prefer to write short clean code, especially to carry out simple processes. The idea was that I have two objects, in this case treeA and treeB and I wanted treeA to be the deeper of the two trees. Now the long way would look something like this:

if treeA.depth < treeB.depth:
    tree = treeA
    treeA = treeB
    treeB = tree

Which is a little ugly, 4 lines to reorder something, so there neat trick is that if you want to swap two objects a and b simply use:

a,b = b,a

So the above code becomes:

if treeA.depth < treeB.depth:
    treeA, treeB = treeB, treeA

Which is much nicer looking. So thats my python tip.

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.