1

I am trying to get the minimum of a list and float, I had the following code but it was giving error

x=['14.99', '14.99', '15.00', '16.36']
y=21.00
min([float(i) for i in x.append(y)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable
#x= ['14.99', '14.99', '15.00', '16.36', 21.0] y got appended  

However, if i do (append y before list comprehension)

x=['14.99', '14.99', '15.00', '16.36']
y=21.00
x.append(y)
min([float(i) for i in x])

Output is :14.99 #correct

How can I do this in one line?

programmerwiz32
  • 529
  • 1
  • 5
  • 20

3 Answers3

3

try this

min(y, min([float(i) for i in x]))

or this one is more readable

min(y, min(map(float, x)))

basically you compare the float y with the minimum of the list.

Emmet B
  • 5,341
  • 6
  • 34
  • 47
1

It's very ugly in my opinion, but you can do it like that:

min([float(i) for i in x+[y])])
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
  • what is a better looking way – programmerwiz32 Jun 24 '19 at 13:23
  • 1
    The "better looking way" is IMHO to keep your original code. It's more readable and should even be more efficient (appending to an existing object instead of creating a new one - or rather two new ones, since you're creating a new list from ``y`` first and then another new list from ``x`` and ``[y]``). – Mike Scotty Jun 24 '19 at 13:25
  • I would use 2 lines to be explicit: `_list = [float(i) for i in x]+[y]` and then `min(_list)`. If you do not care overwriting x, then the code you posted is the best one. – alec_djinn Jun 24 '19 at 13:26
0
x=['14.99', '14.99', '15.00', '16.36']
y=21.00
min(float(x) for x in x+[y])

This concatenates y as a list to the x list, and then finds the min of all of them.

See Allow python list append method to return the new list.

blackbrandt
  • 2,010
  • 1
  • 15
  • 32