Question
Asked By – Amon
I have a piece of my code where I’m supposed to create a switchboard. I want to return a list of all the switches that are on. Here “on” will equal True
and “off” equal False
. So now I just want to return a list of all the True
values and their position. This is all I have but it only return the position of the first occurrence of True
(this is just a portion of my code):
self.states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
def which_switch(self):
x = [self.states.index(i) for i in self.states if i == True]
This only returns “4”
Now we will see solution for issue: Getting indices of True values in a boolean list
Answer
Use enumerate
, list.index
returns the index of first match found.
>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> [i for i, x in enumerate(t) if x]
[4, 5, 7]
For huge lists, it’d be better to use itertools.compress
:
>>> from itertools import compress
>>> list(compress(xrange(len(t)), t))
[4, 5, 7]
>>> t = t*1000
>>> %timeit [i for i, x in enumerate(t) if x]
100 loops, best of 3: 2.55 ms per loop
>>> %timeit list(compress(xrange(len(t)), t))
1000 loops, best of 3: 696 µs per loop
This question is answered By – Ashwini Chaudhary
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0