0

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?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Unpossible
  • 603
  • 6
  • 23

2 Answers2

1

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:])
Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
  • This last is incorrect - inside the function `args` will be a list containing a single (list) element, not a list containing several strings directly. Sina wants to _unpack_ the arguments into the function parameters. – Toby Speight Aug 27 '15 at 07:13
1

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.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103