Optimize apply_templates

Recomputing range(len(X)) for every iteration inside the loop is not necessary, because len(X) is invariant. Furthermore, using lists for membership testing (line 28 in the old version) is O(n), while it is O(1) for sets.

Testing with a sequence of ~46k items, the new code is about 8 times faster on my machine. Diffing the output of the new version and the old version showed that the outputs are the same.