Tuesday, August 3, 2010

My python fix

It has been a while since I did something in Python. I've been coding C++, Qt and Qt Quick lately and I do enjoy it, especially Quick. I really like the declarative way of describing UIs.

But I still need my shot of Python now and then. Often I end up just doing small non useful snippets like list comprehensions stuff. I just love them, they are so beautiful and they make me happy :)
>>> # Find the longest words
>>> words = "Some random words in a text string"
>>> max([(len(w), w) for w in words.split()], key=lambda x:x[0])[1]


  1. Simplified:

    max((w for w in words.split()), key=len)

  2. Sorry, it's 3:15 AM and I should be sleeping.

    Even more simplified: max(words.split(), key=len)

  3. You nailed it! This is why Python is so fun... You often end up doing much more readable code when "optimizing"

  4. Before max() was extended with the key argument, one might have used sorted(words.split(), key=len)[-1]