Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22462

Python Does What?!: List Comprehension Code Golf

$
0
0
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:

>>> [x for x in range(10) if x and x % 2]
[1, 3, 5, 7, 9]

is equivalent to

>>> [x for x in range(10) if x if x % 2]
[1, 3, 5, 7, 9]

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

Viewing all articles
Browse latest Browse all 22462

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>