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?
Python Number min() Method Python number method min() returns the smallest of its arguments: the value closest to negative infinity.
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.
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)
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With