user1707398
user1707398

Reputation: 5

Python: return index of values in a list that are less than a target value using a "while" loop

The program is supposed to take as input a list and return the index of the values less than 0.

I'm not allowed to use for loops, however. I have to do it using a while loop.

For example, if my function were named findValue(list) and my list was [-3,7,-4,3,2,-6], it would look something like this:

>>>findValue([-3,7,-4,3,2,-6])

would return

[0, 2, 5]

So far, I have tried:

def findValue(list):
    under = []
    length = len(list)
    while length > 0:
        if x in list < 0:       #issues are obviously right here.  But it gives you
            under.append(x)     #an idea of what i'm trying to do
        length = length - 1
    return negative

Upvotes: 0

Views: 2170

Answers (2)

Sandeep Kothari
Sandeep Kothari

Reputation: 415

Try this out:

def findValue(list):
    res=[]
    for i in list:
        if i < 0:
            res.append(list.index(i))
    return res

Upvotes: 0

driangle
driangle

Reputation: 11779

I made some small changes to your code. Basically I'm using a variable i to represent the index of element x in a given iteration.

def findValue(list):
    result = []
    i = 0
    length = len(list)
    while i < length:
        x = list[i]
        if x < 0:      
            result.append(i)
        i = i + 1 
    return result

print(findValue([-3,7,-4,3,2,-6]))

Upvotes: 0

Related Questions