I know the point of the piece is the python syntax here, but I got stuck on: "judge things like code quality / speed / conciseness etc." Do people generally write concise code on right off the bat when confronted with a new problem? I've always taken the same approach I would with writing: get something that works; refactor for concision. Maybe everyone else is playing 3D chess and I'm still on Chutes and Ladders?
There are problems I have encountered a billion times and of course I have an elegant concise solution for it, if I am an experienced programmer. if any([a in ["-h", "--help"] for a in args]): display_help() Would be one of those. Generally I learned that it can be beneficial to treat things as lists early on, e.g. if you have a program that takes one input file it costs you next to nothing to allow the input to be m…
`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).