2

As a follow up from this post:

How to return more than one value from a function in Python?

A separate question:

As a beginner programmer, I was taught to only return one thing from a function.

a. Is there any hidden problem with returning more than one thing?

b. If so, and I want to return 2 lists from a long function (ie not call 2 separate similar functions), is there anything wrong with making a tuple out of the lists?

Thanks

Community
  • 1
  • 1
Sammy
  • 669
  • 2
  • 8
  • 13
  • You were probably taught to return one thing because whatever language you were using couldn't handle multiple return values. – user2357112 Sep 05 '13 at 06:26
  • 4
    You always return one thing from a function. This might be a string, a list, a tuple, None, ... Using `return x, y` returns *one* tuple with two elements. – Matthias Sep 05 '13 at 06:33

4 Answers4

6

If returning two things makes sense, yes... return two things.

For example, if you want to split a string based on some criteria, like find key/value pairs, you might call split_string_to_get_key_pair() you would expect it to return a tuple of (key, value).

The question is, is returning a tuple (which is how multiple return values often work) returning one thing or two? An argument can be made either way, but as long as what is returned is consistent and documented, then you can return what ever makes sense for your program.

3

Python encourages returning multiple values if that makes sense. Go for it.

Amber
  • 507,862
  • 82
  • 626
  • 550
3

If you put the two lists into one tuple, you're essentially returning one thing. =D

justhalf
  • 8,960
  • 3
  • 47
  • 74
3

This question is not really specific to Python and is perhaps better suited for Programmers.SE.

Anyway, regarding your questions:

a. Not if these things you are returning are actually a single thing in disguise, and they will be used together most of the time. For example, if you request the color of something, you rarely need only the value of the red channel. So if the returned value is simple enough, or if the wrapping class would not make much sense, you just return a tuple.

b. There isn't, it's a common practice in Python as @Amber has noted.

Community
  • 1
  • 1
fjarri
  • 9,546
  • 39
  • 49