coder123
coder123

Reputation: 27

How do i find one list in another list with python?

I have two lists:

lista=[1,2,3,4,5,6,1,3,2,5,6]

listb=[3,4,5]

I want to find the first occurrence of the elements of listb in the order of listb in lista.

I have tried

print(lista.index(listb))

but it gives the error

ValueError: [3, 4, 5] is not in list

I have also tried

np.where(np.array(lista)==np.array(listb))

but it returns

(array([], dtype=int64),)

What am I doing wrong?

The intended output with lista and listb should be 2.

Upvotes: 0

Views: 184

Answers (4)

Samudra Ganguly
Samudra Ganguly

Reputation: 844

flag2 = False
for i in lista:
    if listb[0] == i:
        c = lista.index(i)
        k = c
        flag = True
        for j in range(len(listb)):
            if listb[j] != lista[c]:
                flag = False
                break
            c = c+1
        if flag:
            flag2 = True
            print(k)
            break
if not flag2:
    print('Does not exist')

Upvotes: 0

Sushil
Sushil

Reputation: 5531

You can use a simple list comprehension:

lista=[1,2,3,4,5,6,1,3,2,5,6]
listb=[3,4,5]

[print(f"Index = {x}") for x in range(len(lista)) if lista[x:x+3] == listb]

Output:

Index = 2

Upvotes: 2

che.wang
che.wang

Reputation: 94

print([lista.index(n) for n in listb])

Upvotes: 0

Siva Shanmugam
Siva Shanmugam

Reputation: 658

If you need index position of your listb in lista.

Code

lista=[1,2,3,4,5,6,1,3,2,5,6]

listb=[3,4,5]

for i in listb:
    if i in lista:
        print (lista.index(i))

Output:

2
3
4

Upvotes: 0

Related Questions