Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: finding lowest integer

I have the following code:

l = ['-1.2', '0.0', '1']  x = 100.0 for i in l:     if i < x:         x = i print x 

The code should find the lowest value in my list (-1.2) but instead when i print 'x' it finds the value is still 100.0 Where is my code going wrong?

like image 501
sarah Avatar asked Apr 12 '10 14:04

sarah


People also ask

How do you return a lesser number in Python?

Python Number min() Method Python number method min() returns the smallest of its arguments: the value closest to negative infinity.

How do you find the smallest and largest number in Python?

Use Python's min() and max() to find smallest and largest values in your data. Call min() and max() with a single iterable or with any number of regular arguments. Use min() and max() with strings and dictionaries.


2 Answers

To find the minimum value of a list, you might just as well use min:

x = min(float(s) for s in l) # min of a generator 

Or, if you want the result as a string, rather than a float, use a key function:

x = min(l, key=float) 
like image 52
Olivier Verdier Avatar answered Oct 06 '22 12:10

Olivier Verdier


You aren't comparing integers, you're comparing strings. Strings compare lexicographically -- meaning character by character -- instead of (as you seem to want) by converting the value to a float. Make your list hold numbers (floats or integers, depending on what you want), or convert the strings to floats or integers in your loop, before you compare them.

You may also be interested in the min builtin function, which already does what your current loop does (without the converting, that is.)

like image 44
Thomas Wouters Avatar answered Oct 06 '22 11:10

Thomas Wouters