How to make a new list of specific sequences from another list?

Viewed 161

I was wondering how I can make a list of pulled specific sequence values (the first three) following a common sequence, to place onto another list. This is more conceptual based versus an actual application if that makes sense. This is an example of what I am trying to accomplish,

seq = 'ATTACGA'
og_list = ['ATGGGCATAGA', 'GCCTGAACTT', 'GAATTACGAAGAGT', 'AAGTCCAAT', 'GCACATTACGATAG']

It would ideally pull the remaining sequence from the common sequence stored in the seq variable to get:

['AGA', 'TAG']

This is because these values are the three after the seq common sequence value. I would imagine the find (.find()) function could be used, but as I am new to Python, if someone can help me figure this out that would be great.

Here is what I have so far:

seq = 'ATTACGA'
og_list = ['ATGGGCATAGA', 'GCCTGAACTT', 'GAATTACGAAGAGT', 'AAGTCCAAT', 'GCACATTACGATAG']
new_list = []
if seq in og_list:
    og_list.find(seq)
    new_list.append(seq)
print(seq)

This is clearly not cutting it. I am unsure of how to get the next three values from the common seq — perhaps slicing might be effective?

3 Answers

You can split the strings by the sequence if it's in the string, and then slice the second part of the results

seq = 'ATTACGA'
og_list = ['ATGGGCATAGA', 'GCCTGAACTT', 'GAATTACGAAGAGT', 'AAGTCCAAT', 'GCACATTACGATAG']
new_list = [x.split(seq)[1][:3] for x in og_list if seq in x]
print(new_list) # ['AGA', 'TAG']

I don't know how long the input list would be, so a generator seems the right approach:

def follow_up(seq, samples, n):
    l = len(seq)
    for s in samples:
        if (p := s.find(seq)) >= 0:
            yield s[p+l:p+l+n]


seq = 'ATTACGA'
og_list = ['ATGGGCATAGA', 'GCCTGAACTT', 'GAATTACGAAGAGT', 'AAGTCCAAT', 'GCACATTACGATAG']

# just collecting in a list here to print the result
print(list(follow_up(seq, og_list, 3)))

Result:

['AGA', 'TAG']

The following very nearly the literal translation of your description of what you want into code (that uses slicing):

target = 'ATTACGA'
og_list = ['ATGGGCATAGA', 'GCCTGAACTT', 'GAATTACGAAGAGT', 'AAGTCCAAT', 'GCACATTACGATAG']

new_list = []
for seq in og_list:
    pos = seq.find(target)
    if pos > -1:
        new_list.append(seq[pos+len(target): pos+len(target)+3])

print(new_list)  # -> ['AGA', 'TAG']

Related