Function returning list is showing False python

57 Views Asked by At

I'm a newbie here, and I am trying to make python recognizes the .split() list inside another. It's a little bit hard to explain, so I will show it:

>>>   #this is a function that separates the last word in the string, spliting the string by words and then transforming it into a list and the using the len() to know what is the position of the last item in the list, so that I can return it to another var.

>>> def lastWord(phrase):
       phrase = list(phrase.split()[len(list(phrase.split()))-1:]))
       return phrase

>>> x = "Hello World"
>>> d = lastWord(x)
>>> d
['World']
>>> x.split()
['Hello', 'World']
>>> one_list ["Hello", "World", "Anything"]
>>> one_list
['Hello', 'World', 'Anything']
>>> x.split() in one_list
False
>>> list(x.split()) in one_list
False
>>> d in one_list
False

How can I make it recognize the generated split list, created using .split() inside another list??

3

There are 3 best solutions below

0
On

Problem because you are trying to find ['Hello', 'World'] in ["Hello", "World", "Anything"]

Will give you True when

one_list = [["Hello", "World"], "Anything"]
0
On

Change the following -

x.split() in one_list

to -

exists = True
for item in x.split():
    if item not in one_list:
        exists = False
        break
print exists
0
On

You can't use "in" like that to test for each individual item:

x.split() in one_list

Try with this:

all(x in one_list for x in x.split())