0

The title ^. For some reason the code I have now is allowing words to slip through that evidently don't contain the required letters.

listOfValid = ["xxxxy", "xxxxz", "xxxxx", "a", "ab"]
lettersIn = ["a", "b"]

for word in listOfValid:
    for letter in lettersIn:
        if letter not in word and word in listOfValid:
            listOfValid.remove(word)

print(listOfValid)

This returns: 'xxxxz' 'a' 'ab'. Why is it allowing xxxxz and a through?

HB1327
  • 19
  • 1
  • 2
    Why are you checking `and word in listOfValid:` ? you take `word`from this list! – Patrick Artner Feb 14 '22 at 12:57
  • 1
    Why do you iterate a list and modify it. That is a big NO-NO. – Patrick Artner Feb 14 '22 at 12:58
  • That might be because you're modifying the list that you're iterating through. Try creating a new empty list and use `append` to add values to the new list. Also you'll have to change your condition to the opposite (`letter in word`) – aaossa Feb 14 '22 at 12:58

2 Answers2

1

Perhaps you wanted to do this?

listOfValid = ["xxxxy", "xxxxz", "xxxxx", "a", "ab"]
lettersIn = ["a", "b"]

for word in listOfValid[:]:
    for letter in lettersIn:
        if letter in word:
            break
    else:
        listOfValid.remove(word)

print(listOfValid)

Try it online!

You can't iterate on an array that you are modifying, so listOfValid[:] copies the array.

Although you should probably do something more like this:

listOfValid = ["xxxxy", "xxxxz", "xxxxx", "a", "ab"]
lettersIn = ["a", "b"]

listOfValid = [*filter(lambda i:any(map(lambda l:l in i,lettersIn)),listOfValid)]

print(listOfValid)

Try it online!

AnttiP
  • 306
  • 2
  • 6
1

Using list compreenssion this should work:

[x for x in listOfValid if x in lettersIn]
Franz Kurt
  • 1,020
  • 2
  • 14
  • 14