1

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:

def scrollList(myList):
      negativeIndices = []
      for i in range(0,len(myList)):
            if myList[i] < 0:
                 negativeIndices.append(i)
      return negativeIndices
2
  • 9
    Why do you need to do this? Is there some secondary problem you're trying to solve? Commented Sep 26, 2012 at 21:23
  • What university do you attend? Commented Sep 27, 2012 at 4:10

5 Answers 5

5

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

10 Comments

I think this illustrates why a normal python for loop is the right thing, though
It can also be a very simple list comprehension one-liner.
Yep, check my answer. I +1'd you, btw.
Why in the world would anyone prefer this over incrementing a counter?
@EdS. Well, the whole idea of rewriting a for loop as a while loop is either silly or a learning exercise. Hope for the "learning exercise" died 41 minutes ago when the answer was spoon-fed to the OP, so we're left with "silly."
|
1

like this:

def scrollList(myList):
      negativeIndices = []
      i = 0
      while i < len(myList):
            if myList[i] < 0:
                 negativeIndices.append(i)
            i += 1
      return negativeIndices

6 Comments

Adding a loop variable just makes into a secret for loop, so it's not really a conversion, just an inefficient and hard to read for loop.
yes captain obvious but that's what the OP asked for so I showed him how to do it. Stop hating on people and messing with their reputabion get a life
No, he didn't ask you to implement a for loop with the while statement. I'm not hating on you, I downvoted an answer I didn't find helpful, as you are supposed to do. I'm hating on your reaction, though, which is stupid.
That's exactly what the OP asked for: " I am needing to convert a for loop to a while loop". I'm sorry I got angry but I did exactly what the OP asked for so I don't believe my answer should be downgraded.
@LennartRegebro Your philosophical objection to the index variable creates an interesting coding problem... how do you convert this for loop into a while loop without "implementing the for loop"?
|
-1
def scrollList(myList):
      negativeIndices = []
      while myList:
          num = myList.pop()
          if num < 0:
             negativeIndices.append(num)
      return negativeIndices

4 Comments

I too the freedom to improve your code. You don't need to do len() and compare it to 0.
actually your code is bad because it empties the list while in the OP's original code the list stayed intact.
@IonutHulub: That's true, making a copy would be an idea.
In an effort to avoid the index variable, you ended up doing something completely differently from what the original code does.
-2

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

1 Comment

1. Adding a loop variable just makes into a secret for loop, so it's not really a conversion. 2. Your syntax is broken. This is Python, not javascript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.