3
listEx = ['cat *(select: "Brown")*', 'dog', 'turtle', 'apple']
listEx2 = ['hampter',' bird', 'monkey', 'banana', 'cat']

for j in listEx2:
    for i in listEx:
        if j in i:
            print listEx.index(j)

What I am trying to accomplish is search the items in listEx2 in listEx. If the item from listEx2 is found in listEx, I would like to know how to print the index value of the item found from listEX2 in listEx. Thanks!

2
  • 1
    Do you want 'cat' to be found because it is contained within 'cat *(select: "Brown")*'? Commented Nov 13, 2011 at 21:53
  • What should happen if there are multiple items in listEx containing the string "cat"? Do you want the index of all of them? Commented Nov 13, 2011 at 21:59

2 Answers 2

4

Just use enumerate:

listEx = ['cat *(select: "Brown")*', 'dog', 'turtle', 'apple']
listEx2 = ['hampter',' bird', 'monkey', 'banana', 'cat']

for j in listEx2:
    for pos, i in enumerate(listEx):
        if j in i:
            print j, "found in", i, "at position", pos, "of listEx"

This will print

cat found in cat *(select: "Brown")* at position 0 of listEx
Sign up to request clarification or add additional context in comments.

1 Comment

Why am I always so slow? :( - Whatever, your solution is good and works.
3

Your problem is that you wrote j instead of i in the last line:

for j in listEx2:
    for i in listEx:
        if j in i:
            print listEx.index(i)
#                              ^ here

However, a better approach is to use enumerate:

for item2 in listEx2:
    for i, item in enumerate(listEx):
        if item2 in item:
            print i

2 Comments

Please don’t just catch any exception, but only look for ValueError. – edit: Thanks xD
I want to find the index of 'cat (select: "Brown")'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.