2

I would like to assign two quantities to the variables min and max, depending on their value. Suppose f is a function which returns an integer value. Is there any way I can do something like

min, max = f(1), f(2)

which accounts for the values of f(1) and f(2)? Clearly the above assigns f(1) to min and f(2) to max regardless of their value.

Luke Collins
  • 1,433
  • 3
  • 18
  • 36

2 Answers2

3

You can just sort an iterable of the return values before assigning them to min_v and max_v.

min_v, max_v = sorted((f(1), f(2)))

If you had a small iterable of return values (but more than 2), using extended iterable unpacking might be alright.

min_v, *_, max_v = sorted(map(f, some_small_list))

But of course if you applied f to a list of any considerable length, it is far more efficient to pluck out the min and max with the built-ins (which you shouldn't shadow) rather than sort and unpack.

miradulo
  • 28,857
  • 6
  • 80
  • 93
-2

You can do something like:

min, max = (f(1),(f2)) if f(1)<f(2) else (f(2),f(1))

If this is what you were looking for.

sourabh
  • 48
  • 5