0

How to do something like this in python

def func1():
    x = 2
    y = 3
    return x, y

def funcx():
    print(func1().x)

def funcy():
    print(func1().y)

So basically return multiple values from a single function then use each returned value in a different function

2
  • 1
    Just as any other tuple. Commented Nov 11, 2018 at 11:56
  • @usr2564301 thanx for the tip Commented Nov 11, 2018 at 15:39

1 Answer 1

2

Python functions can return only one value, but it is easy for that value to contain others. In your example, func1 returns a single tuple, which in turn contains two values.

>>> def func1():
...     x = 2
...     y = 3
...     return x, y
...
>>> func1()
(2, 3)

You can index or unpack this return value just like any other tuple:

>>> func1()[0]
2
>>> func1()[1]
3
>>> a, b = func1()
>>> a
2

You can use indexing also in your desired functions:

def funcx():
    print(func1()[0])

def funcy():
    print(func1()[1])

If you desire named fields, you can use a dict or namedtuple:

# dict
def func1():
    return {'x': 2, 'y': 3}

def funcx():
    print(func1()['x'])

# namedtuple
from collections import namedtuple

Point2D = namedtuple('Point2D', ['x', 'y'])
def func1():
    return Point2D(x=2, y=3)

def funcx():
    print(func1().x)
Sign up to request clarification or add additional context in comments.

Comments

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.