Reputation: 46423
I would like my function to return 1, 2, or 3 values, in regard to the value of bret
and cret
.
How to do something more clever than this ? :
def myfunc (a, bret=False, cret=False):
b=0
c=0
if bret and cret:
return a,b,c
elif bret and not cret:
return a,b
elif not bret and cret:
return a,c
else:
return a
Upvotes: 4
Views: 272
Reputation: 3699
Please note if you have to return tuple (in your question it returns tuple) use this -
def myfunc(a, bret=False, cret=False):
return tuple([a] + [0 for i in (bret, cret) if i])
Upvotes: 1
Reputation: 33
You could return a list. Look:
def myfunc (a, bret=False, cret=False):
list = []
list.append(a)
b=0
c=0
if bret:
list.append(b)
if cret:
list.append(c)
return list
Solve your question?
Upvotes: 1
Reputation: 9077
def myfunc(a, bret=False, cret=False):
return [v for v, ret in [(a, True), (0, bret), (0, cret)] if ret]
Take a moment to read about Python List Comprehensions. They are handy very often!
Upvotes: 2
Reputation: 500277
How about:
def myfunc(a, bret=False, cret=False):
...
return (a,) + ((b,) if bret else ()) + ((c,) if cret else ())
Upvotes: 4
Reputation: 23
You might simply append your return
values to a list or use yield
.
You can iterate over the result afterwards and do what you please.
Here's an explanation to the yield
-Keyword: What does the "yield" keyword do in Python?
Upvotes: 1
Reputation: 239453
def myfunc (a, bret=False, cret=False):
b, c, ret = 0, 0, [a]
if bret: ret.append(b)
if cret: ret.append(c)
return ret
Upvotes: 3