-1

Possible Duplicate:
Converting a for loop to a while loop

I have this for a for loop which I made I was wondering how I would write so it would work with a while loop.

def scrollList(myList):
    negativeIndices=[]
    for i in range(0,len(myList)):
        if myList[i]<0:
            negativeIndices.append(i)
    return negativeIndices

So far I have this

def scrollList2(myList):
    negativeIndices=[]
    i= 0
    length= len(myList)
    while i != length:
        if myList[i]<0:
            negativeIndices.append(i)
            i=i+1

    return negativeIndices
7
  • 1
    @user1690198 I'd look at how for loops work first - loop directly over the list, not over a range of indicies. ([index for index, value in enumerate(myList) if value < 0]) Commented Sep 26, 2012 at 22:41
  • 1
    scrollList = lambda lst: [i for i,v in enumerate(lst) if v<0] Commented Sep 26, 2012 at 22:42
  • This was just asked by another user. You guys should not use SO to do your homework. Commented Sep 26, 2012 at 22:57
  • @IgnacioVazquez-Abrams It's homework. Commented Sep 26, 2012 at 23:08
  • 2
    @IgnacioVazquez-Abrams: Or at least for teaching them to write for i in range(x): … x[i] … loops… Commented Sep 27, 2012 at 0:04

2 Answers 2

6

Well, you are nearly there. It's like this:

def scrollList2(myList):
    negativeIndices=[]
    i= 0
    length= len(myList)
    while i != length:
        if myList[i]<0:
            negativeIndices.append(i)
        i=i+1

    return negativeIndices

The problem you had is that you must increment the loop index on each iteration. You were only incrementing when you found a negative value.


But it's better as a for loop and your for loop is over complicated. I'd write it like this:

def scrollList(myList):
    negativeIndices=[]
    for index, item in enumerate(myList):
        if item<0:
            negativeIndices.append(index)
    return negativeIndices
Sign up to request clarification or add additional context in comments.

Comments

2

Well, for one, your incrementer i should always be updated, instead of just when you meet the condition. Only doing it in the if statement means you're only ever advancing when you see a returnable element, so if your first element doesn't meet your condition, your function will hang. Oops. This would work better:

def scrollList2(myList):
    negativeIndices=[]
    i= 0
    length= len(myList)
    while i != length:
        if myList[i]<0:
            negativeIndices.append(i)
        i=i+1

    return negativeIndices

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.