0

For these lists:

a=['applepearstrawberry','applepearbanana','orangekiwiapple','xxxxxxxxxxx']
b=['apple','pear']

How do you return a list with any elements that contain 'apple' or 'pear'.

DESIRED OUTPUT

c=['applepearstrawberry','applepearbanana','orangekiwiapple']

Attempted solution:

c=[]
for i in a:
    if b[0] or b[1] in a:
        c.append(i)
print(c)

Thankyou

GDog
  • 163
  • 9
  • 2
    Your code is fine, except that you need to check `b[0] in a or b[1] in a`. `b[0] or b[1] in a` will almost always be `True`. Does this answer your question? [Why does \`a == x or y or z\` always evaluate to True?](https://stackoverflow.com/questions/20002503/why-does-a-x-or-y-or-z-always-evaluate-to-true) – Pranav Hosangadi Jun 28 '21 at 18:46

2 Answers2

5

Use any():

a = ["applepearstrawberry", "applepearbanana", "orangekiwiapple", "xxxxxxxxxxx"]
b = ["apple", "pear"]

out = [v for v in a if any(w in v for w in b)]
print(out)

Prints:

['applepearstrawberry', 'applepearbanana', 'orangekiwiapple']
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

Your statement if b[0] or b[1] in a: contains a common mistake. Python interprets this line as if (b[0]) or (b[1] in a):, which will be true anytime b[0] is not empty.

You could fix this by using if b[0] in a or b[1] in a:. But if b might not have two values, you're better off using one of these:

if any(w in a for w in b):

or

for w in b:
    if w in a:
        c.append(w)
        break

Or, for a simple one-liner based on any, see Andrej Kesely's solution.

Matthias Fripp
  • 17,670
  • 5
  • 28
  • 45