Gazza732 Gazza732 - 4 days ago 5
Python Question

How do I use the output of a function as the input for another function inside a function

I am currently studying Python and hoping someone could help me.
I'm fairly new to coding so would be really helpful if its explained well.

Lets say I have a function called

function1
that returns:

return (row, column)


Now I am writing another function called say
function2
.
Within this function I need to call say:

exampleItem.exampleName(row, column, name)


How do I use the output of the
function1
which is the row and column as the
row
and
column
arguments in the above line from
function2
?

I really hope this makes sense as I got seriously penalized for not writing a question properly before because I didn't realize the best practice here.

Answer

You could use * to unpack the result (which is a tuple) of the first function call and thereby provide the resulting elements as positional arguments in the second:

exampleItem.exampleName(*function1(), name)

In Python 2.x you can do the same but, you need to supply the remaining positional arguments in keyword form in order to get it to work with *:

exampleItem.exampleName(*function1(), name=name)

this also works on Python 3.x so you have no issues with portability.

of course, unpacking in a previous statement with row, column = function1() and then providing them to the second function by position with:

exampleItem.exampleName(row, column, name)

is another option. It falls down to preference in the end :-)

Comments