2

If I have a function which supports variable argument number, i.e. uses *args, how can I populate the arguments from a loop/list comprehension? Say the function expects multiple lists as arguments and I have a table/dataframe and want to use each column as an input argument, why does this not work?

funName([df[iCol].values for iCol in df.columns])

Say my dataframe has 5 columns, I would be required to call the function like so:

funName(col1, col2, col3, col4, col5)

But I do not want to manually create variables for each column but rather populate the argument list dynamically. Thanks.

1 Answer 1

6

Unpack your list when passing it in:

funName(*[df[iCol].values for iCol in df.columns])

List unpacking is required because if you don't, fn will get a single argument, which is a list, say [1, 2, 3], and you want a sequence of arguments 1, 2, 3.

For example:

>>> def fn(*args):
...     print args
...     
>>> fn([1, 2, 3])
([1, 2, 3],)
>>> fn(*[1, 2, 3])
(1, 2, 3)
>>> 
Sign up to request clarification or add additional context in comments.

3 Comments

Works perfectly. Thanks! Why is list unpacking required? (will accept the answer in 11 mins).
@dter That's the syntax
Makes sense. Basically identifying whether the 1,2,3 is 3 different arguments or 1 argument list containing [1,2,3] as elements.

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.