Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a list to function with variable number of args in python [duplicate]

Tags:

python

I have to write a simple function that takes variable number of arguments and prints the sum, something simple like(ignoring error checks):

def add(*params):
    sum = 0
    for num in params:
        sum += num
    print(sum)

I have to call the script and give it arguments that will then be used in the function. I get these arguments like this:

import sys
sys.argv[1:]

But that's an array and sending it to add would just mean passing 1 argument that is a list. I'm new to Python so maybe all of this sounds stupid, but is there any way to pass these arguments to the function properly?

like image 414
Angelo Avatar asked Nov 12 '18 13:11

Angelo


2 Answers

Yes, just unpack the list using the same *args syntax you used when defining the function.

my_list = [1,2,3]
result = add(*my_list)

Also, be aware that args[1:] contains strings. Convert these strings to numbers first with

numbers = [float(x) for x in args[1:]]

or

numbers = map(float, args[1:]) # lazy in Python 3

before calling add with *numbers.

Short version without your add function:

result = sum(map(float, args[1:]))
like image 176
timgeb Avatar answered Oct 13 '22 23:10

timgeb


You should use the argument unpacking syntax:

def add(*params):
    sum = 0
    for num in params:
        sum += num
    print(sum)

add(*[1,2,3])
add(*sys.argv[1:])

Here's another Stack Overflow question covering the topic

like image 25
rjmurt Avatar answered Oct 13 '22 22:10

rjmurt