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)
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)