Wednesday, February 3, 2016

List Comprehension Code Golf

Ah code golf, pastime of our navelgazing alter egos. Being designed for readability and maintainability, Python doesn't always show well in this sort of sport, but occasionally we get thrown a bone. For instance, for nonzero even numbers less than 10:

>>> [x for x in range(10) if x and not x % 2]
[2, 4, 6, 8]

is equivalent to

>>> [x for x in range(10) if x if not x % 2]
[2, 4, 6, 8]

A whole character saved! Yes, a close reading of PEP 202 will show that one of the canonical examples of list comprehensions uses this pattern for... some reason.

Either way, now you know. Sally forth and do what must be done with all code golf tricks: Never, Ever Use Them For Production Code.

-- Mahmoud
http://sedimental.org/
https://github.com/mahmoud
https://twitter.com/mhashemi

3 comments:

  1. I just wanna say thanks for providing such a useful information, and I really appreciate your effort you help many student to resolving their development related queries. If there is any who still facing problem check out the link below.
    https://eazyresearch.com/services/buy-essay

    ReplyDelete
  2. Just contact our siteDo My Essay For Me, and you will approach the schoolwork task help of these extraordinary experts from the UK, the USA, and different nations. It doesn't make any difference whether you are in Singapore or Canada, you'll find the opportunity to have your task in on schedule.

    ReplyDelete
  3. You're faultlessly expected to start your voucher and view full holding course, exchange your multi-choice voucher or exchange and progression your experience
    By: https://www.certaxlondon.co.uk/

    ReplyDelete