For instance I have a list A
:
A = [100, 200, 300, 200, 400, 500, 600, 400, 700, 200, 500, 800]
And I have list B
:
B = [100, 200, 200, 500, 600, 200, 500]
I need to identify the index of elements in B
with comparison to A
I have tried:
list_index = [A.index(i) for i in B]
It returns:
[0, 1, 1, 5, 6, 1, 5]
But what I need is:
[0, 1, 3, 5, 6, 9, 10]
How can I solve it?
By using the list. index() method, we can easily get the element index value from list. In this example we have define a list of integer values and uses the list. index() method we can get the index of the item whose value is '210'.
However, because Python lists can contain duplicate items, it can be helpful to find all of the indices of an element in a list. Let’s get started! Before diving into how to get the index positions of all elements in a Python list, let’s take a quick moment to understand how Python lists are indexed.
Given a list, the task is to write a Python Program to get the indices of all occurrences of an element in a list. This is a simple method to get the indices of all occurrences of an element in a list. Here we use a for-loop to iterate through each element in the original list. Instead of using for-loop we can use enumerate function.
It takes two optional arguments which are indices at which search has to start and stop in the list. If the input element exists in the list between the specified indices, the index() method returns the index of the element where it occurs first. We can observe this in the following example.
Output: List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23] Number is: 2 Indices of 2 are [1, 8] Conclusion In this article, we have used different ways to find the indices of an element in a list.
You can iterate through the enumeration of A
to keep track of the indices and yield the values where they match:
A = [100,200,300,200,400,500,600,400,700,200,500,800]
B = [100,200,200,500,600,200,500]
def get_indices(A, B):
a_it = enumerate(A)
for n in B:
for i, an in a_it:
if n == an:
yield i
break
list(get_indices(A, B))
# [0, 1, 3, 5, 6, 9, 10]
This avoids using index()
multiple times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With