user6515864
user6515864

Reputation:

How to check if a word is in a list and if it exists in an item of the list then get the index number of the item

I have a list called A

A = ["How are you","I am good","What are you doing?"]

I want to search for a word "good" and if it is found in the list then i want to get the item's index number in which the word has been found.

Desired output:

A = ["How are you","I am good","What are you doing?"]

B = "good"

Result =>

"good" word was found in list A[1]

i want to get the index number of the list's item in which the word was found.

Upvotes: 0

Views: 726

Answers (2)

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

A = ["How are you","I am good","What are you doing?"]
B = "good"
d = [(i, a) for i, a in enumerate(A) if B in a]
print("Elements found", d[0][-1]) #printing what elements contain "good"
print("'{}' was found in list A[{}]".format(B, d[0][0]) if d else "'{}' not found".format(B))

Output:

'Elements found', 'I am good'
'good' was found in list A[1]

Upvotes: 0

Ben10
Ben10

Reputation: 498

Try this (I made a function):

A = ["How are you","I am good","What are you doing?"]
B = "how"

def FindWordInList(list,item):
    index = 0
    for string in list:
        index += 1
        for word in string.split():
            if word.lower() == item:
                #Subtracts one from the list as list index starts at 0
                return index - 1

    print("Could not find the word {} in the list".format(item))

indexofword = FindWordInList(A,B)
print("{} word was found in list A[{}]".format(B,indexofword))

Hope this helps!

Upvotes: 1

Related Questions