errrr.... it's actually a good question... x)
3 years later, I'd actually say it's perfectly fine in this situation (I guess I had in mind something about saturation of the memory with the extra list, but in most situations you won't see any problem. Now, if n is huge, you'll run into troubles anyway, but not necessarily because of the approach itself, but rather because of the size of the string you have to build...)
ccl: forget that message.
Could you elaborate on which specific aspect of the above code is dangerous or footgun-y?
I just can't believe, simple like that.
I say this in 7 out of 10 cases when i see solution from other people :))))
It does the job. Check out other solutions.
REGEX ... "Regexp Basics"
you are missing the point
Join puts a separator (here '\n') between the elements of an iterable, so not at the beginning nor at the end.
It's clever but not the best practice. It lacks readability.
It's still O(n).
It's fine! Learning is what's important :)
Thanks @Kacarott, I really didn't know. Thanks for that lesson.
@geans You are overlooking one important thing. map does NOT go through the whole list. It creates a generator, which produces values one at a time, which feeds into the other functions, which short circuit.
Here is proof:
while True: yield 1
a = map(lambda x: x*2, infinite()) # Works instantly
b = [x*2 for x in infinite()] # Loops forever (timeout)
man, just read my comment again: there is no difference in the present context...