I've heard couple of times already that you shouldn't do string concatenation in a for loop as strings are immutable and so it would compute the concatenation as a new string instance and then reassign the identifier. So if the result has n characters the time complexity would be O(n^2)
Bad: runs in O(n^2). Iterative '+' concatenation.
letters = ""
for c in document:
if c.isalpha():
letters += c
Good: runs in O(n). Iterative append, with a final "".join()
document = ""
temp = []
for c in document:
if c.isalpha():
temp.append(c)
letters = "".join(temp)
At the same time I've read that
"Some later implementations of the Python interpreter have developed an optimization to allow such code to complete in linear time,.."
So the first solution should be fine too? Is it an optimization which is in the latest python builds?