Reputation: 33
Here's the original code:
def scrollList(myList):
negativeIndices = []
for i in range(0,len(myList)):
if myList[i] < 0:
negativeIndices.append(i)
return negativeIndices
and here's what i've got so far:
def scrollList2(myList):
negativeIndices = []
needMoreNumbers = True
while (needMoreNumbers):
if myList[i] < 0:
negativeIndices.append(i)
n = n-1
if (n<1):
needMoreNumbers = False
return negativeIndices
Right now I'm getting the error "global name 'i' is not defined which I know it's not but I don't know how to go about defining 'i' without a for loop. Thanks
Upvotes: 0
Views: 112
Reputation: 8448
Well, you can try manually doing indexation.
def scrollList2(myList):
negativeIndices = []
index = 0
while (index < len(myList)):
if myList[index] < 0:
negativeIndices.append(index)
index+=1
return negativeIndices
Upvotes: 0
Reputation: 1056
the pythonic answer is
indices = [i for i,n in enumerate(mylist) if n<0]
or use () instead of [] for a generator (to dynamically generate them one by one)
Upvotes: 0
Reputation: 35970
The reason you're getting a global error on i
is that you've not defined it anywhere. You have to define what you use. You've also not defined the variable n
. After fixing i
you'll get an error on that too.
So, define n
in front of the while
loop like so
n = len(myList)
while(needsMoreStuff):
and change the reference to i
to be
if myList[n] < 0:
negativeIndices.append(n)
should suffice to fix your error.
Edit:
Suggested a different looping construct and then edited it to be more in keeping with the question. Problem is an undeclared variable.
Upvotes: 1
Reputation: 29794
Just simulate it with a counter variable:
def scrollList2(myList):
negativeIndices = []
counter = 0
while (counter < len(myList)):
if myList[counter] < 0:
negativeIndices.append(counter)
counter += 1
return negativeIndices
Upvotes: 0