I'm not sure what the grand scheme is, but you can write it in a way that will likely be faster:
Here, assuming you are building a string:
exclude = set(list('{}[]')) # note: set is faster than list for membership test
mk = ''.join([idx for idx in tf if idx not in exclude])
# 61 ms on a 1M-char random string
exclude = '{}[]' # ...but string is even faster, when so short
mk = ''.join([idx for idx in tf if idx not in exclude])
# 38 ms on a 1M-char random string
By the way, it will be considerably faster to achieve the same by letting the large loop (on all chars of tf
) be done by builtin functions, and just iterate on the chars to exclude:
mk = tf.replace('{', '').replace('}', '').replace('[', '').replace(']', '')
# 11.8ms on 1M chars
And yet faster:
mk = tf.translate({ord(c): None for c in '{}[]'})
# 4.5 ms on 1M chars
Setup (if anyone is interested to look for yet a faster way):
tf = ''.join(np.random.choice(list('abcdefghijk{}[]'), size=1_000_000))