-1

I want to ask if i can return more than one value using function. when i make a function that is not necessarly returning one value like the swap functin,I'm not sure how to deal with it.Because in the end i want to return the two variables, let us consider them x and y

To explain more i tried to do this little function:

Function Swap(x:integer,y:integer)
Variables
temp:integer
Begin
temp=x
x=y
y=temp
return x,y

the thing that I'm not sure about is if i have the right to** return more than one value**?

  • 1
    short answer is yes you can return multiple values packed in a tuple or list using a function. there is a simpler way to do this in python `x, y = y, x` is exactly the same as what you did in swap function. – anmol_gorakshakar Dec 12 '22 at 22:32
  • 1
    Functions **always** return a *single* value. That value may be an *iterable*, like a `tuple` or a `list`, in which case, you can use iterable unpacking in the caller. In any case, did you *try* to a write a function taht returned a tuple? What happened when you tried? Also, a swap function is pretty pointless in Python, you can just use the swap idiom directly, `x, y = y, x` – juanpa.arrivillaga Dec 12 '22 at 22:32
  • i got what you are saying. and i know that in python using swap function is pointless. I'm just a litte bit confused when I'm writing a pseudocode if i have the right to return the x and y at the same time or not – saad elmoraghi Dec 12 '22 at 22:35
  • yes you should write x, y as it primes the reader of your code to expect multiple return arguments. But honestly it is a subjective especially for pseudocode. – anmol_gorakshakar Dec 12 '22 at 22:42
  • Does this answer your question? [Is it pythonic for a function to return multiple values?](https://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values) – storenth Dec 14 '22 at 15:46
  • Is your question about Python or pseudocode? If it is about Python, please write correct Python. – Gelineau Dec 15 '22 at 09:44

1 Answers1

1

You could just try it:

def some_func():
  return 4, "five", [6]

a, b, c = some_func()
print(f"{a}, {b}, {c}")
>>> 4, five, [6]

Yes, you can return as many values from a func as you like. Python will pack all the return values into a single var, a tuple, and allows you to unpack them into multiple vars when the function returns. So, you could also do:

  d = some_func()
  print(type(d))
  >>> <class 'tuple'>
  print(d)
  >>> (4, 'five', [6])
Danielle M.
  • 3,607
  • 1
  • 14
  • 31