Atonal Atonal - 7 months ago 11
Python Question

Python 2.7x generators to return indexes of "False"s in a Boolean list

I'm trying to write a function to return the indexes of the 'False' values in an arbitrary list. I also would like to use generators for this.

I wrote below:

def cursor(booleanList):
for element in booleanList:
if element is False:
yield booleanList.index(element)


So for example I have the list below

testList = [True, False, True, False]


And then:

g = cursor(testList)


However if I use my code, I would get:

> g.next()
1
> g.next()
1
> g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration


Whereas I expect to get:

> g.next()
1
> g.next()
3
> g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration


Where's the problem in the code? Any help would be much appreciated.

Answer

Look at the documentation of .index(x), it returns the index of the first item whose value is x. This explains why your generator is always yielding 1.

Instead, you may use enumerate() like this:

def cursor(booleanList):
  for index, element in enumerate(booleanList):
    if element is False:
      yield index
Comments