python-2.7multiple-arguments

Multiple arguments passed from user input remain as single argument


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?


Solution

  • The return value from split is a list:

    >>> values = '1 2 2 4h 5'.split()
    >>> values
    ['1', '2', '2', '4h', '5']
    

    When you call foo, you're passing that list as a single argument, so foo(values) is the same as foo(['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:

    >>> print foo(*values)
    (('2', '2', '4h', '5'), <type 'tuple'>)
    

    See Unpacking Argument Lists in the Python Tutorial.