Reputation: 55
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
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
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
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
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
Reputation: 99
Why use a for loop ?
Just use:
xs=[5,3,2,5,6,1,0,5]
print min(xs)
Upvotes: 0
Reputation: 10716
Use the min
method:
xs=[5,3,2,5,6,1,0,5]
print min(xs)
This outputs:
0
Upvotes: 2