0

I want to remove character from string seq_in = 'KPKPAJDSKGRPRRKAPPP' at specific indices in the list ind = [0, 1, 2, 3, 8, 10, 11, 12, 13, 14, 16, 17, 18]. The result should be 'AJDSGA'. I tried remove() the string by looping the ind list, but each character's index was shifted.

How to remove many characters at index from the list without loop?

1 Answer 1

3

You can use a generator expression within join using enumerate to get the index of each letter. If the index isn't in ind then keep it.

>>> ''.join(j for i,j in enumerate(seq_in) if i not in ind)
'AJDSGA'

As mentioned in the comments, your lookups will be faster if ind is a set than if it stays a list

>>> ind = {0, 1, 2, 3, 8, 10, 11, 12, 13, 14, 16, 17, 18}
>>> ''.join(j for i,j in enumerate(seq_in) if i not in ind)
'AJDSGA'
Sign up to request clarification or add additional context in comments.

1 Comment

suggestion: make ind a set

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.