Kenneth
Kenneth

Reputation: 3

Getting min value from a list using python

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())

Upvotes: 0

Views: 68

Answers (2)

Dugbug
Dugbug

Reputation: 454

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

Upvotes: 0

azro
azro

Reputation: 54168

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

Upvotes: 4

Related Questions