Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
def minval(xs):
    minum = xs[0]
    for i in range(len(xs)):
        if xs[i] < minum: #difference in code: xs[i]
            minum = xs[i]
    return minum

or

def minval(xs):
    minum = xs[0]
    for i in range(len(xs)):
        if i < minum: #difference in code: i
            minum = xs[i]
    return minum

It gives me the same results:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]

print minval(lst)

1

Which one is better? Why do they both give the same result?

Is there a better more shorter way to get the same result, without resorting to pythons own functions?

Edit: I got it why it works, I ran the second one, it looped through the "i" which was just the numbers from the range of the len of xs and not the actual indexes of xs.

share|improve this question
4  
What's wrong with Python's built-in function min? –  Gareth Rees Nov 10 '13 at 12:38
add comment

2 Answers

A slight improvement would be:

def minval(xs):
    minimum = xs[0]
    for x in xs[1:]:
        if x < minimum:
            minimum = x
    return minimum

In general you should loop through the values in a list rather than finding the range and then looping through the indices. If you really need the indices you can also use enumerate.

But as others have said, you would simply use min for this.

share|improve this answer
add comment

They aren't the same: The second gives -1 for [-1,-2,-3] and is simply spuriously correct, while the first gives the correct answer.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.