Search code examples
pythonlistfunctiontuplesargs

what type of data do *args accept? The function works with direct input, but errors if tuples/lists variables are entered (below: "numbers")


def add_unlimited(*args):
    sum = 0
    for n in args:
        sum += n
    print(sum)
    
    
numbers = [23, 45, 23, 56]  
add_unlimited(23, 45, 23, 56)

Solution

  • def add_unlimited(*args) accepts an arbitrary amount of arguments. Inside the function, the arguments are accessible in the form of a list, which is named args.

    Note that add_unlimited([23, 45, 23, 56]) is calling the function with one argument. That argument happens to be a list, [23, 45, 23, 56]. Inside the function, this will result in args = [[23, 45, 23, 56]]. The rest of your code inside the function doesn't work if each argument is not an integer, which is why you get an error.

    You can pass a single list as several arguments by using the unpacking operator *:
    add_unlimited(*[23, 45, 23, 56]) is equivalent to add_unlimited(23, 45, 23, 56)