Wednesday, February 28, 2024

*args to accept any number of positional arguments

 Consider the below case:

We need to all the sum all the inputs. Number of inputs are unknown.

sum(5,8,9)
The above will not work. sum() takes at most 2 arguments (3 given).

But, sum() can calculate the sum of Iterable i.e. means List, Tuple etc.

sum([5,8,9])
or
sum((5,8,9))
* means any number of arguments.
def sum_of_nums(*args):
print(args) -> o/p: (3, 8, 8, 190)
print(type(args)) -> <class 'tuple'>
return sum(args)


print(sum_of_nums(3, 8, 8, 190))

No comments:

Post a Comment