Home > Mobile >  what type of data do *args accept? The function works with direct input, but errors if tuples/lists
what type of data do *args accept? The function works with direct input, but errors if tuples/lists

Time:10-08

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)

CodePudding user response:

Please note that *args does not have any type restriction, unlike other static languages like Go. You can even mix tuples of lists of integers, and plain strings together. This is equivalent to type annotating it like *args: Any - signifying that each argument can be any type.

However, in this case, it looks like your function depends on each argument being a number. So I would type annotate it like *args: Number, to hint to the caller that each argument passed in should be a valid number.

Usage can be as below:

from numbers import Number


def add_unlimited(*args: Number):
    sum = 0
    for n in args:
        sum  = n
    print(sum)


numbers = [23, 45, 23, 56]
add_unlimited(*numbers)

CodePudding user response:

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)

CodePudding user response:

sum=0
for n in args:
    sum = 0   [23, 45, 23, 56] 

you can't add a list and zero.

you probably wanted something like

for x in args:
    for n in x:
        sum  = n
  • Related