Multiple arguments passed from user input remain as single argument

1.1k views Asked by At

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?

2

There are 2 answers

0
Toby Speight On BEST ANSWER

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.

1
Aswin Murugesh On

If multiple values are entered in the same line, you have to take the entire set in a single list in Python. You can split it afterwards by the way.

values = raw_input().split()
value1 = values[0]
del values[0]

This will give you the desired result

Or if you just want to send it to a function seperately,

values = raw_input().split()
myfunc(values[0],values[1:])