0

I am not sure what I'm doing wrong, but I keep getting an Index error whenever I try to run the code.

def min_valueinlist(bag = [1,-1,3,4,5,6]):
    bag_length= len(bag)
    counter = 1
    min_value = bag[0]
    while counter <= bag_length:
        v = bag[counter]
        if (v < min_value):
            min_value = v
        else:
            pass
        counter=counter+1
    return min_value
    

print(min_valueinlist())
3

2 Answers 2

4

As arrays are 0-indexed, the last index is 1 off the length

values  [1, -1, 3, 4, 5, 6]
indices  0   1  2  3  4  5  # and len() is 6

  • so your loop should use < and not <=
  • else:pass is useless
  • there is a buitin min()
while counter < bag_length: # and not <=

When you need to iterate on values only and don't need their indices, prefer a for loop

def min_valueinlist(bag=[1, -1, 3, 4, 5, 6]):
    min_value = bag[0]
    for v in bag:
        if v < min_value:
            min_value = v
    return min_value
Sign up to request clarification or add additional context in comments.

Comments

0

Python already has a min() function that does this for you:

# Creating a function that takes one parameter
def get_minumum_value_in_list(list):
    return min(list)  # Returning the minimum value in the list using min()


print(min([1, -1, 3, 4, 5, 6])) # Executing function

Comments

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.