2

I have a list that is basicaly zeroes and ones, I want to grab all the indices of the ones from that list. How do I do it, plz. If possible, w/o loops.

list_example = [1,0,0,1,0,0,0,1,1,0]
StupidWolf
  • 45,075
  • 17
  • 40
  • 72
AAA Yerus
  • 31
  • 4
  • 1
    What have you tried so far? – Klaus D. Dec 28 '19 at 02:37
  • 3
    Use a list comprehension and the `enumerate()` function. – Barmar Dec 28 '19 at 02:38
  • Not that it necessarily can’t be done without loops but... why? Why is that the goal? – Jab Dec 28 '19 at 02:49
  • If you consider a list comprehension to be a loop, my suggestion won't work. You can use `enumerate`, `filter`, and `map` to do it. – Barmar Dec 28 '19 at 02:52
  • [Four methods](https://www.geeksforgeeks.org/python-ways-to-find-indices-of-value-in-list/). The 4th uses filter so it does it using only built-in functions (i.e. without looping in user code). – DarrylG Dec 28 '19 at 02:53
  • Does this answer your question? [How to find all occurrences of an element in a list?](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – FatihAkici Dec 28 '19 at 03:24

4 Answers4

0

You could use np.argwhere() to obtain incides in a list whose elements satisfy a certain condition. Below's the code:

import numpy as np
np.argwhere(np.array(list_example))[0]

Output:

[0, 3, 7, 8]

where we obtain indices of all non-zero elements in list_example. For more specific condition checking, you could use,

np.argwhere(np.array(list_example==1))
Balraj Ashwath
  • 1,407
  • 2
  • 13
  • 19
  • The condition is always 'Find the indices of array elements that are non-zero, grouped by element.' from https://docs.scipy.org/doc/numpy/reference/generated/numpy.argwhere.html ;) – azro Dec 28 '19 at 15:34
0

you can use list comprehension:

ones_indices = [i for i, e in enumerate(list_example) if e == 1]
kederrac
  • 16,819
  • 6
  • 32
  • 55
0

Without loops or imports you can do it this way:

list(zip(*list(filter(lambda x: x[1] == 1, enumerate(list_example)))))[0]
# (0, 3, 7, 8)

or if you want lists:

list(map(list, zip(*list(filter(lambda x: x[1] == 1, enumerate(list_example))))))[0]                                                                                               

# [0, 3, 7, 8]
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
0

my attempt so far:

g = [0,0,1,0,1,0,0,1,1,0,0,0,1,0]
u = []
   for i in g:

    if i == 1:
        u.append(g.index (i))

print (u)
input ('continue')
AAA Yerus
  • 31
  • 4