1

How can i reduce this condition ?

item is always a string

for item in list_of_items:
    if ('beans' in item or 'apple' in item or 'eggs' in item or 'banana' in item) and ('elephant' not in item) or 'chicken' not in item:
                print(item)

I mean can I somehow give list of words to check every possibility?

1
  • set(list_of_items).intersection({'beans', 'apple', 'eggs', 'banana'}) Commented Mar 13, 2019 at 9:29

3 Answers 3

3

You can use any with a generator or list comprehension:

if any(word in item for word in ['apple', 'beans', 'eggs', 'banana', 'elephant', 'chicken')):
Sign up to request clarification or add additional context in comments.

1 Comment

Except a missing ]
1

You can use any for the first part.

However the second part cannot be reduced

if any(w in item for w in ('beans', 'apple', 'eggs', 'banana')) and ('elephant' not in item) or 'chicken' not in item:

Not useful for your case but you should be aware that all is also useful.

You can reduce this if 'a' not in item and 'b' not in item to if all(w not in item for w in ('a', 'b')

Comments

1

Using list-comprehension:

good_items = ['beans','apple','eggs','banana', 'elephant', 'chicken']
list_of_items = ['apple', 'grapes', 'elephant', 'chicken']

print([x for x in list_of_items if x in good_items and x not in ['elephant', 'chicken']])

OUTPUT:

['apple']

1 Comment

Note the parentheses. The condition is ('elephant' not in item) or 'chicken' not in item not ('elephant' not in item or 'chicken' not in item)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.