4

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
4
  • I'm not sure you want that. What if next question will be how to handle tuples with different lengths? Commented Dec 7, 2013 at 13:58
  • @alko Yup - especially for the two-form return where whether it's b or c is lost... Commented Dec 7, 2013 at 14:01
  • you are always returning a, a,0 or a,0,0 Commented Dec 7, 2013 at 14:32
  • this is just an example @aro, in my real code b and c are more interesting values... Commented Dec 7, 2013 at 16:14

6 Answers 6

4

How about:

def myfunc(a, bret=False, cret=False):
   ...
   return (a,) + ((b,) if bret else ()) + ((c,) if cret else ())
Sign up to request clarification or add additional context in comments.

Comments

3
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

Comments

2
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!

Comments

1

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?

Comments

1

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?

2 Comments

no, the problem is not having a list. The problem is that this won't work anymore if 3 conditions, then there would be 2^3=8 cases to distinguish ! not beautiful ;)
This is equivalent to a much earlier solution posted by @thefourtheye (and I'd recommend against calling the variable list since this shadows the built-in function.)
1

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])

2 Comments

This returns bret/cret instead of b/c.
Return value is always - a, a,0 or a,0,0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.