June 11, 2008

This is Python, intro

Writing in Python for a few years now, I still get a kick of it. Wonderful and very powerful language, if used in the right way (aren't they all like that ?). No matter if code base is in megabytes, I still occasionally sit back in silence, admiring the beauty of a little code fragment or the way an idea is expressed in code.

If there is one single snippet of Python code to introduce its power of simplicity, it would be swapping of two variables. When I found it long ago in Python cookbook, it hit me like thunder. Never was my understanding of Python the same as before.

Here goes. To swap two variables in Python you need to

a, b = b, a

This utilizes Python feature called automatic tuple packing/unpacking. What's actually going on is more like

a, b <<< unpacked <<< (b, a) <<< packed <<< b, a

where (b, a) is a Python notion for an immutable sequence called tuple.

To be continued...

No comments: