keven ren keven ren - 7 months ago 20
Python Question

Accessing objects and tuples from a function

I have a feeling there should be a very easy way to access specific elements from an evaluated function. A very simple example of what I am trying to achieve is

def func(x):
a = 2*x
b = x*x
return 1, 10, 100, (a,b)

I define a value for x and the function returns a set of values and a tuple. I would like to retrieve (for example) the first element and the tuple. Code such as

hello, cello = func(2)[[0,3]]

Returns an error. However I can access these elements individually,

bello = func(2)[3]

for example.

The function I am using takes a while to evaluate so making it run twice is not a desirable option. Furthermore, if possible I would not like to create a pile of variables for each individual element of the tuple (contains many).

In essence I would like a solution that is along the lines of:

hello, cello = func(2)[[0,3]]


hello = 1
cello = (4,4)



So you can unpack and ignore:

hello, _, _, cello = func(2)

But if the result is more complicated you can use operator.itemgetter:

from operator import itemgetter
hello, cello, bello = itemgetter(0, 3, 15)(func(2))

Or more verbosely:

my_results = itemgetter(0, 3, 15)
hello, cello, bello = my_results(func(2))