Question

I have two lists, one of the form:

lst = [">ctgxxxx1/n", "aatttata", ">ctgxxxx2/n", "attggag", ">ctgxxxx3/n", "ggagttata"]

and another of the form

ATP6 = [ ">ctgxxxx1/n", ">ctgxxxx3/n"]

For every item in lst that is also found in ATP6 I want to append "ATP6" to the end of the item in lst. In this example I would like the output of the code to be:

lst = [">ctgxxxx1ATP6/n", "aatttata", ">ctgxxxx2/n", "attggag", ">ctgxxxx3ATP6/n", "ggagttata"]

Currently I have the following code:

for x in lst:
    if x.startswith(">"):
        if x in ATP6:
            x = x+"ATP6"

This however isnt having any effect at all.

I assume its not working because I have a nested if statement but Im not sure. As well as an answer could I have an explanation of why my code doesnt work to help me learn. Thankyou!

Was it helpful?

Solution 2

Your problem, as mentioned in the comments, is because you're modifying a copy of the element in your array, not the original. Additionally, you can shorten your code to a more pythonic list comprehension like so:

lst = [x+'ATP6' if x in ATP6 else x for x in lst] 

OTHER TIPS

Your code does not do what you want because you attempt to modify an immutable type (string) in your loop. This will create a new object instead of changing the sting in place.

I'd use a list comprehension:

>>> lst = [lstitem+'ATP6' if lstitem in ATP6 else lstitem for lstitem in lst]

yields:

['>ctgxxxx1/nATP6',
 'aatttata',
 '>ctgxxxx2/n',
 'attggag',
 '>ctgxxxx3/nATP6',
 'ggagttata']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top