Reputation: 31
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:
ListA
which is also in ListB
is 1
.1
in ListA
is 1
.Upvotes: 1
Views: 70
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
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
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
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