1

How do I iterate through two lists without the use of nested "for" loops?

the index between the two lists doesn't necessarily have to be the same

more specifically I am coding a function that takes a list of strings and a list of banned words. If any of the banned words are in each one of the strings, that whole string gets deleted.

I tried doing:

for word in bannedWords:
    for string in messages:
        if word in string:
            messages.remove( string )

This, however, doesn't work because the string variable is used in the "for" loop, so removing the string from messages will mess up the "for" loop. What is a better way to implement? Thanks.

bariox
  • 13
  • 3
  • It seems to me you need the nested 'for' loop to do what you want. Your issue is actually: "How do I delete an item from a list while iterating over it?". You can find some answers here: http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python – Mel May 25 '16 at 18:08

3 Answers3

2

You could probably do it in a line!

messages = [string for string in messages 
              if not any(word in bannedWords for word in string)]
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
1

I would probably write something like:

def filter_messages(messages, bannedWords):
    for string in messages:
        if all(word not in string for word in bannedWords):
            yield string

Now you have a generator function that will only give you good messages. If you really want to update messages in place, you can do:

messages[:] = filter_messages(messages, bannedWords)

though the in-place requirement is rare:

messages = list(filter_messages(messages, bannedWords))
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

Assuming a set of banned words and a list of strings that might contain these bad words:

bannedWords = set("bad", "offensive")

messages = ["message containing a bad word", "i'm clean", "i'm offensive"]

cleaned = [x for x in messages if not any(y for y in bannedWords if y in x)]

Result:

>>> cleaned
["i'm clean"]
>>> 
jDo
  • 3,962
  • 1
  • 11
  • 30