user1005970
user1005970

Reputation: 1

How to check if a string from a list is inside another list?

Lets say i have 2 lists:

a=['LOL','GG','rofl']
b=['5 KEK muh bobo LOL', 'LOL KEK bobo bobo GG']

How do i check if first element in a can found in first element of b?

Upvotes: 0

Views: 122

Answers (4)

Scott A
Scott A

Reputation: 7844

If you only need to know if it's in the string or not:

if a[0] in b[0]: pass

However, the above has the problem that both of these will return true:

if "LOL" in "a b LOL c": pass
if "LOL" in "a b xxLOLxx c": pass

So if you care about words vs. simple presence, as long as your delimiters are consistent:

if a[0] in b[0].split(" "): pass

If you need to know which word position:

idx = b[0].split().index(a[0]) # note, throws a ValueError if not in the list

If you need to know the position in the string:

idx = b[0].find(a[0]) # returns -1 if not found

If you want to know if each element from a is in the corresponding element of b (ignores extra entries on either list):

[(i[0] in i[1]) for i in zip(a, b)] # to check for simple membership
[(i[0] in i[1].split()) for i in zip(a, b)] # to check for whole words

Upvotes: 1

JBernardo
JBernardo

Reputation: 33407

Just that:

a[0] in b[0] # will return True or False

maybe you want to check all of them:

set(i for i in a for j in b if i in j)

or

{i for i in a for j in b if i in j} #Python 2.7+

Upvotes: 4

Nicola Coretti
Nicola Coretti

Reputation: 2685

You can simply do:

a[0] in b[0]

which will return a True if the first element of a can be found in the first element of b, otherwise it will return False.

Upvotes: 0

Tyler Ferraro
Tyler Ferraro

Reputation: 3772

Python is actually very robust. You can just do.

a[0] in b[0]

Upvotes: 2

Related Questions