Vitali Kazinski
Vitali Kazinski

Reputation: 31

Finding index of number from another list

I am using Python 3, and I have two lists in my code:

ListA = [53, 1, 17, 4, 13, 2, 17]
ListB = [4, 3, 1]

Now, I want to find the index of any number in ListB that is in ListA.

The output in this case should be 1 because:

Upvotes: 1

Views: 70

Answers (4)

blhsing
blhsing

Reputation: 107095

You can use the following generator expression:

next(i for i, a in enumerate(ListA) for b in ListB if a == b)

Given your sample input, this returns: 1

Upvotes: 1

blhsing
blhsing

Reputation: 107095

If you want better efficiency you can turn ListB into a set so that you can determine if an item is in ListB with an average time complexity of O(1):

setB = set(ListB)
print(next(i for i, a in enumerate(ListA) if a in setB))

This outputs: 1

Upvotes: 1

mad_
mad_

Reputation: 8273

Set intersection to find the common values. Then find all the indices which are present in ListA and then find the minimum index. If in case there is no match it will print the length of ListA

set_inter =set(ListB).intersection(ListA)

if set_inter: # if there is a common value
    idx_A=min([ListA.index(i) for i in set_inter])
    print(idx_A)
else:
    print(len(ListA)) # print the length of ListA

Upvotes: 0

jpp
jpp

Reputation: 164823

In pure Python, you can use a generator comprehension with next and enumerate:

A = [53, 1, 17, 4, 13, 2, 17]
B = [4, 3, 1]
B_set = set(B)

first_lst = next(idx for idx, val in enumerate(A) if val in B_set)  # 1

Note we hash values in B via set to optimise lookup cost. Complexity is O(m + n), where m and n are number of elements in A and B respectively. To error handle in case no match is found, you can supply a default argument:

first_list = next((idx for idx, val in enumerate(A) if val in B_set), len(A))

If you are happy to use a 3rd party library, you can use NumPy. No error handling here in case of no match:

import numpy as np

A = np.array([53, 1, 17, 4, 13, 2, 17])
B = np.array([4, 3, 1])

first_np = np.where(np.in1d(A, B))[0][0]  # 1

Upvotes: 2

Related Questions