0

If I have a list:

A = [1,1,1,0,0,1,0]

How can I return the index of any occurence of the number 1?

With this example, how to return the following:

[0, 1, 2, 5] 

This is because the number 1 appears specifically in these parts of the list

1 Answers1

0

You can use a simple list comprehension:

A = [1,1,1,0,0,1,0]

i = [i for i,v in enumerate(A) if v==1]
[0, 1, 2, 5]
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
  • Could you provide an explanation for how enumerate works here? Is it sort of like a second index? –  Dec 17 '21 at 13:00
  • It creates a list of `tuples` with each element and its associated index e.g. `enumerate([1,2,2,3])` would become `[(0,1),(1,2),(2,2),(3,3)]` the first number is the index and the second is the value. You can read more about it [here](https://docs.python.org/3/library/functions.html#enumerate) – Pedro Maia Dec 17 '21 at 13:04
  • How would this look in a function without enumerate? –  Dec 17 '21 at 13:34
  • You'd need to iterate over the range of the len: `i = [i for i in range(len(A)) if A[i]==1]` – Pedro Maia Dec 17 '21 at 13:38