I am trying to understand the mechanics of passing multiple arguments to a python function. (I am using Python 2.7.9)
I am trying to split multiple user input arguments passed into a function, but they all just get passed in as a single argument of the first value:
def foo(first,*args):
return args, type(args)
values = raw_input().split()
print(foo(values))
After saving this to a file and running python <name of file>.py
, I have this output:
$python testfunction.py
1 2 2 4h 5
(['1', '2', '2', '4h', '5'], <type 'list'>)
((), <type 'tuple'>)
But if I call foo directly, inside the script like this:
def foo(first,*args):
return args, type(args)
print(foo(1, 2, 3, 4, 5))
then I get what I want:
$ python testfunction.py
(1, <type 'int'>)
((2, 3, 4, 5), <type 'tuple'>)
None
Please why does this happen, and how can I get the second case to happen when I accept user input?
The return value from
split
is a list:When you call
foo
, you're passing that list as a single argument, sofoo(values)
is the same asfoo(['1', '2', '2', '4h', '5'])
. That's just one argument.In order to apply the function to a list of arguments, we use a
*
inside the argument list:See Unpacking Argument Lists in the Python Tutorial.