0

I have a simple array like this

x=[0,0,0,1,1,1,2]

I would like to know, the number 1 is in what index. So far, when I am doing this:

a = ["a", "b", "b", "d", "e"]
print(a.index("b"))

from the code above the result is 1, is there a way to get the result that 1 is in index 1 and 2

wahyu
  • 1,679
  • 5
  • 35
  • 73
  • 2
    How do your `x` and `a` lists relate to each other? It's not quite clear. – AKX Apr 23 '21 at 06:44
  • 4
    `[i for i,val in enumerate(a) if val=='b']` – kiranr Apr 23 '21 at 06:45
  • Does this answer your question? [Finding the index of an item in a list](https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list) – sushanth Apr 23 '21 at 06:47
  • @AKX I am sorry, ```x``` and ```a``` are 2 different example. so in ```x``` I would like to find index for ```1``` and for list of ```a``` I would like to find index of ```b``` – wahyu Apr 23 '21 at 06:52
  • @sushanth I just take a look to the link that you have given, and yes.. that question is related to my case and I also found answer there, thank you very much... – wahyu Apr 23 '21 at 06:59

2 Answers2

3

As pointed out in the comments, a linear approach for random data uses enumerate and a comprehension:

a = ["a", "b", "b", "d", "e"]

b_indeces = [i for i, v in enumerate(a) if v == "b"]
# [1, 2]

You can do better, however, if the data is sorted (as in the given examples), using bisect to find the left and right boundaries of the index range:

from bisect import bisect, bisect_left

b_indeces = list(range(bisect_left(a, "b"), bisect(a, "b")))
# [1, 2]
user2390182
  • 72,016
  • 6
  • 67
  • 89
2

As @waveshaper suggested one way of doing it can be,

x=[0,0,0,1,1,1,2]
a=x;
print([i for i,val in enumerate(a) if val==1])

output:

[3, 4, 5]

It returns a list of index values where your data is present and in this case data is 1

Prathamesh
  • 1,064
  • 1
  • 6
  • 16