Hacker News new | past | comments | ask | show | jobs | submit login

Fun Python fact time!

`any` works on arbitrary iterables, so you can use a generator comprehension instead of a list comprehension:

  if any((a in ["-h", "--help"] for a in args)):
      display_help()
Which algorithmically is a wash, because the time you save not-materializing the list, you waste in the overhead of iterating through a generator (and it's all +/- nanoseconds in recent versions of Python anyway). However, Python has a special syntax that allows you to omit a layer of parentheses when a generator comprehension is the only argument to a function, leaving us with the very elegant (IMO) syntax:

  if any(a in ["-h", "--help"] for a in args):
      display_help()
This works for any(), all(), str.join(), and others. Yet another demonstration of why I think the iteration protocol is one of the best features in Python (and underappreciated as such).



ah cool, I didn't realize




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: