I am new to Python and I need to convert a for
loop to a while
loop and I am not sure how to do it. This is what I am working with:
The problem here is not that you need a while loop, but that you should use python for loops properly. The for loop causes iteration of a collection, in the case of your code, a sequence of integers.
for n, val in enumerate(mylist):
if val < 0: negativeindices.append(n)
enumerate
is a builtin which generates a sequence of pairs of the form (index, value)
.
You might even perform this in a functional style with:
[n for n, val in enumerate(mylist) if val < 0]
This is the more usual python idiom for this sort of task. It has the advantage that you don't even need to create an explicit function, so this logic can remain inline.
If you insist on doing this with a while loop, here's one that take advantage of python's iteration facilities (you'll note that it's essentially a manual version of the above, but hey, that's always going to be the case, because this is what a for loop is for).:
data = enumerate(list)
try:
while True:
n, val = next(data)
if val < 0: negativeindices.append(n)
except StopIteration:
return negativeindices
def scrollList(myList):
negativeIndices = []
while myList:
num = myList.pop()
if num < 0:
negativeIndices.append(num)
return negativeIndices
Just setup a variable for the loop and increment it.
int i = 0;
while(i<len(myList)):
if myList[i] < 0:
negativeIndices.append(i)
i++;
return negativeIndices
like this:
def scrollList(myList):
negativeIndices = []
i = 0
while i < len(myList):
if myList[i] < 0:
negativeIndices.append(i)
i += 1
return negativeIndices
The first answer is the straightforward way, there is another way, if you're allergic to incrementing your index variables:
def scrollList(myList):
negativeIndices = []
indices = range(0,len(myList)):
while indices:
i = indices.pop();
if myList[i] < 0:
negativeIndices.append(i)
return negativeIndices