I frequently find myself in situations where I want to assign to a variable based upon the outcome of some comparison or other logic. I've done some Googling and I know that I CAN assign None
to a variable and then assign to it later, but I just want to know if that's really the best way.
Here is an example of what I have in mind:
def function(v1, v2):
least = None
if v2 < v1:
least = v2
else:
least = v1
Something in my mind is telling me there must be a better way, but I definitely wouldn't call myself an expert in Python.
CodePudding user response:
I wouldn't write the first assignment since it's immediately overwritten and the code's guaranteed to take one of the two branches.
def function(v1, v2):
if v2 < v1:
least = v2
else:
least = v1
You can shorten it to a one-liner if you like.
def function(v1, v2):
least = v2 if v2 < v1 else v1
It's a matter of taste whether this is better or worse than the previous version. I like it, but it quickly becomes unreadable as the logic gets more complicated.
CodePudding user response:
There's no need to assign it first in your example, because all branches of the condition assign it.
Assigning a default value first is necessary if there could be code paths that don't assign the variable. A common situation is if you assign the variable in a loop; if the loop executes zero times, you won't set the variable.
def function(lst):
result = None
for item in lst:
if somefunc(item):
result = item
return result
If you don't initialize result
before the loop, you'll get an error if the list is empty or none of the elements satisfy the somefunc()
condition.