Python Prettiness
Whilst in Melbourne, and on the recommendation of Anthony Baxter (current Python release manager) I picked up a copy of O’Reilly’s Python Cookbook, it’s certainly a worthwhile read. In it, I found the most beautiful piece of Python code I’ve seen in a long time:
def qsort( L ): if len( L ) <= 1: return L return qsort( [i for i in L[1:] if i <= L[0]] ) + [L[0]] + \ qsort( [i for i in L[1:] if i > L[0]] )
For those of you who don’t recognise it, it’s an implementation of Quicksort, and a particularly inefficient one, at that. What is nice about it is how it shows off the expressive power of Python’s list comprehensions. The example in the Cookbook credits the Haskell Web Site for the inspiration for the code (Haskell, incidentally is where the idea of list comprehensions came from in the first place)
It’s worth noting that it’s not a piece of code that I’d use in real life, but as an example, it’s certainly interesting.
If you’re interested in the original recipe from the cookbook, you can find it at the Online Python Cookbook.