user1701501
user1701501

Reputation: 11

Converting a for loop to a while loop

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

Upvotes: 1

Views: 4080

Answers (5)

Marcin
Marcin

Reputation: 49816

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

Upvotes: 5

user1691717
user1691717

Reputation: 223

def scrollList(myList):
      negativeIndices = []
      while myList:
          num = myList.pop()
          if num < 0:
             negativeIndices.append(num)
      return negativeIndices

Upvotes: -1

trutheality
trutheality

Reputation: 23465

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

Upvotes: 3

krb686
krb686

Reputation: 1796

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

Upvotes: -2

Ionut Hulub
Ionut Hulub

Reputation: 6326

like this:

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

Upvotes: 1

Related Questions