Eddy221
Eddy221

Reputation: 55

python: How to compare elements within one list

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!

Upvotes: 2

Views: 28383

Answers (7)

Bharati
Bharati

Reputation: 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

Upvotes: -1

Sam Mussmann
Sam Mussmann

Reputation: 5983

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)

Upvotes: 0

Subbu
Subbu

Reputation: 2101

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)

Upvotes: 3

Viren Rajput
Viren Rajput

Reputation: 5736

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

Upvotes: 0

Vorsprung
Vorsprung

Reputation: 34327

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)

Upvotes: 0

Michiel Rop
Michiel Rop

Reputation: 99

Why use a for loop ?

Just use:

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

Upvotes: 0

jrd1
jrd1

Reputation: 10716

Use the min method:

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

This outputs:

0

Upvotes: 2

Related Questions