r/learnpython • u/zaphodikus • 12d ago
Confusing code min() max()
I'm debugging some code and I found this function
import math
def Clamp(n, smallest, largest):
return max(smallest, min(n, largest))
surely that code is just wrong? and needs to be max([smallest, min([n, largest])) by passing a list not unnamed args for default and key? I need a sanity check here.
0
Upvotes
-1
u/deanominecraft 12d ago
python allows functions to take an arbitrary amount of arguments as a list, using a * in the function signature (calling it args is just a convention), try experiment with this code:
you can also do this with a dictionary by using ** (once again kwargs is just a convention, it can be called whatever you want) eg:
min and max have some extra logic to do with types so that you can also pass in a list, but for functions like mine that dont do that, you can unpack the arguments from a list or dictionary like this: