-1

I think the solution here is trivial, but I cant get it. How to match a string against a list item? No matter how many list items match, it should just return True (or False if there is no match).

Below code returns True:

txt = ["to","do","list","to","test","it"]

x = "to"

if x in txt:
    print("match")
else:
    print("no match")

But this one returns False:

txt = ["to,do,list","to,test,it"]

x = "to"

if x in txt:
    print("match")
else:
    print("no match")

This also returns false:

txt = ["todolist","totestit"]

x = "to"

if x in txt:
    print("match")
else:
    print("no match")

ADaren
  • 9
  • 2

2 Answers2

1

You got False because x in txt looks for an exact match, the list has several items and it searches if any of it is the one you want

What you want to is : search if any of the list items contains your string

values = ["to,do,list","to,test,it"]
word = "to"

if any(word in value for value in values):
    print("match")
else:
    print("no match")

So you may better understand, this is equivalent to

for value in values:
    if word in value:
        print("match")
        break # not need to continue
else:
    print("no match") # in case no break was use
azro
  • 53,056
  • 7
  • 34
  • 70
-3

The key difference in your examples is that in the first one, txt is a list of separate strings, while in the second and third examples txt contains only a single string in each element.

The in operator checks if the exact string exists in the list. So in the first case, "to" matches one of the list elements. But in the second and third cases, there is no exact "to" string in the list.

To check if a substring exists in the list strings, you need to iterate through the list and use the in operator on each element:

txt = ["to,do,list","to,test,it"] 

x = "to"

for item in txt:
    if x in item:
        print("match")
        break
else:
    print("no match")
    
SWARNAVA DUTTA
  • 163
  • 1
  • 3
  • 1
    You don't need to write the solution 3 times ;) – azro Jul 29 '23 at 07:55
  • The code I gave is for 3 separate cases to show that the change made in the code will give correct output in all cases – SWARNAVA DUTTA Jul 29 '23 at 07:58
  • You don't need to, that makes the answer too much verbose and less readable, if the user had given 10 cases he failed to, would you have written 10 times your EXACT same code ? – azro Jul 29 '23 at 08:00