Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python two lists finding index value

Tags:

python

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!

like image 832
phales15 Avatar asked Jul 18 '26 04:07

phales15


2 Answers

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
like image 116
Tim Pietzcker Avatar answered Jul 19 '26 16:07

Tim Pietzcker


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
like image 26
Mark Byers Avatar answered Jul 19 '26 16:07

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!