1

I'm trying to find the minimum value in a list using a for loop but I'm not getting the right answer.

This is what I am doing:

xs=[5,3,2,5,6,1,0,5]

for i in xs:
    if xs[i]< xs[i+1]:
        print(i)

edit: sorry i should've said this earlier but I'm not allowed to use the min function!

2
  • Iteration over a list returns its items not indexes. Commented Oct 27, 2013 at 19:28
  • 3
    How about using the min function? Commented Oct 27, 2013 at 19:28

7 Answers 7

3

If you want to use for loop , then use following method

xs=[5,3,2,5,6,1,0,5]
minimum = xs[0];
for i in xs:
    if i < minimum:
        minimum = i ;
print(minimum)

Without loop , you can use the min method

minimum = min(xs)
print(minimum)
Sign up to request clarification or add additional context in comments.

Comments

2

Use the min method:

xs=[5,3,2,5,6,1,0,5]
print min(xs)

This outputs:

0

Comments

0

Why use a for loop ?

Just use:

xs=[5,3,2,5,6,1,0,5]
print min(xs)

Comments

0

I assume you intend to find successive elements that are in lesser to greater order. If this is the case then this should work

for i in xrange(len(xs)-1):
    if xs[i]< xs[i+1]:
        print(i)

Comments

0
>>> xs=[5,3,2,5,6,1,0,5]
>>> print min(xs)
#Prints 0

Comments

0

You could do this without a for loop and without min() using the built-in function reduce():

minimum = reduce(lambda x, y: x if x < y else y, xs)

Comments

-1

You can try this

    xs=[5,3,2,5,6,1,0,5]
    minvalue=xs[0]      #Assuming first value in xs as minimum value
    for i in range(0,len(xs)):
        if xs[i]< minvalue:     #If xs[i] is less than minimum value then
            minvalue=xs[i]      #minmumvalue=xs[i]
    print(minvalue)             #print minvalue outside for loop

Output: 0

1 Comment

Thry that with xs=[2,0,2] or even xs=[2,0,3].

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.