Yianni S Yianni S - 2 months ago 7
Python Question

Looking to simplify multiple variables in if statement

I attempted to simplify this code:

for word in wordlist:
if (word != 'a' and
word != 'i' and
word != 'and' and
word != 'this' and
word != 'is' and
word != 'in'):


into

commom_words = ['a', 'i', 'and', 'this', 'is', 'in]

for word in wordlist:
if word != any(common_words):


I also tried
all(common_words)
.

Using the original code, the common words were omitted from my search of the text. When I tried to simplify them in the variable, the common words were getting through if the statement.

Answer

The easiest approach would probably be to use the not in syntax:

common_words = ['a', 'i', 'and', 'this', 'is', 'in']
for word in wordlist:
    if word not in common_words:
        # Do something with it...