-1

I tried to remove and element from t, based on whether it is present in s, this is the code I wrote, however 'd' is not being removed. So my question is. Why is 'd' not being removed from t when it certainly is not in s?

def isSubsequence(s: str, t: str) -> bool:
    
    s = list(s)
    t = list(t)

    for i in t:
        if i not in s:
            t.remove(i)

    print(t)

isSubsequence('abc', 'ahbgdc')

Output:

['a', 'b', 'd', 'c']
Jesse
  • 1
  • 4
    Don't modify a list while you are iterating over it. Instead, build a new list with the parts you want to keep. – Tim Roberts Aug 01 '22 at 18:22
  • Welcome to Stack Overflow. It's not clear exactly how you want the question answered, so I offered multiple relevant duplicate links. It seems as though you only create lists because you expect them to be necessary in order to process the strings. It's true that Python's strings are immutable, but there is still a much more direct way to filter characters out of a string, so I linked that one. In case you still want to know about lists: the title question "how to remove the elements?" is different from the body question "why doesn't this work?", with separate existing questions for each. – Karl Knechtel Aug 01 '22 at 18:37

2 Answers2

0

Build a new list with the winners:

def isSubsequence(s: str, t: str) :
    n = []
    for i in t:
        if i in s:
            n.append(i)
    return ''.join(n)

print(isSubsequence('abc', 'ahbgdc'))

Or, fancier:

def isSubsequence(s: str, t: str):
    return ''.join( i for i in t if i in s )
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • You have 9 years of experience on the site, have attained every privilege that reputation affords, and have a gold badge in the Python tag that allows you (like me) to close questions as duplicates unilaterally. Please help make the site more searchable by linking duplicates and helping to remove bad signposts, not less by putting effort into answers that interfere with the [roomba](https://stackoverflow.com/help/roomba). – Karl Knechtel Aug 01 '22 at 18:41
  • If you prefer the experience of tailoring answers to common programming questions, to novices who have asked them fresh in some specific way, there are plenty of discussion forums out there that will be overjoyed to accept that kind of help. Stack Overflow is not one of them. While we accept arbitrarily "easy" questions, they need to be original and in some way useful. – Karl Knechtel Aug 01 '22 at 18:43
-1

You could use a single line to build a new list over which you are not iterating:

def isSubsequence(s: str, t: str) -> bool:
    l = [i for i in t if i not in s]

    print(l)

isSubsequence('abc', 'ahbgdc')
Blue Owl
  • 119
  • 12