Home > Software design >  Pythonic way to get minimum nonzero value or zero, if it does not exist
Pythonic way to get minimum nonzero value or zero, if it does not exist

Time:05-20

I have a problem finding the correct way to do this in python:

I have a list of two numbers which are Positive numbers including Zero

This is what I want:

  • If both numbers are greater than zero, I want the minimum one

  • If one is Zero and the other is greater than zero, I want the one that is greater than zero

  • and if both are zero, I want zero

How do I do this without writing Ifs: following would be an example:

if list[0]>0 and list[1]>0 : answer = min(list)
if list[0] >0 xor list[1]>0 : answer = max(list)
else: answer = 0 

Thanks in advance

CodePudding user response:

Filter out your zeros and take the min of that. If the resulting iterable is empty have min() return a default value.

answer = min((x for x in yourlist if x != 0), default=0)

CodePudding user response:

One way:

a, b = lst
min(a or b, b or a)

Another:

min(lst) or max(lst)

Both use that x or y results in x if it's true (nonzero) and y otherwise.

  • Related