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

1 comment:

  1. CIITN is the best SAP training and placement Institute in noida. Contestant will analyze in keeping with modern-day enterprise trends by way of certified and industry experts & SAP training Institute in Noida. They provide a 100% placement help with the best training of IT cousrses.

    If you are looking best sap training in Noida then you can join CIITN. One of the premier training and development institute for SAP Training Program in Noida. The company provides 6 weeks/ 6 Months Training for SAP. They provide training in all SAP Modules like SAP HANA,SAP B1, SAP FICO etc. Just come for free demo class and then join SAP and move up in your career .

    SAP Training Institute in Noida
    sap training in noida
    sap institute in noida
    sap course in noida
    best sap training institute in noida