Atonal
Atonal

Reputation: 530

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.

Upvotes: 1

Views: 134

Answers (3)

Apollo2020
Apollo2020

Reputation: 519

As an extension of the previous answers you may also use a generator expression. Admittedly this is a more tailored solution but perhaps applicable to your use case. Just out of curiosity, why do you want to use a generator if you already have the list in memory?

testList = [True, False, True, False]

g = (i for i in range(len(testList)) if testList[i] is False)

for i in g:
    print i

Upvotes: 1

fukanchik
fukanchik

Reputation: 2865

This is your list with indexes [0:True, 1:False, 2:True, 3:False] now booleanList.index searches for the first False in the list and returns the index which of course is always 1.

You mistakengly think that for element in booleanList: somehow exhausting the booleanList but it is not.

You need to use ranged for instead:

def cursor(booleanList):
  for index in range(0, len(booleanList):
    if booleanList[index] is False:
      yield index


testList = [True, False, True, False]

g = cursor(testList)

print g.next()
print g.next()
print g.next()

Upvotes: 0

Delgan
Delgan

Reputation: 19627

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

Upvotes: 1

Related Questions