Unlimited Arguments
#Previous method
def add(n1, n2):
return n1 + n2
add(n1=2, n2=5)
#*Args
def add(*args):
print(arg)
add(3, 5, 6)
--------------------
(3, 5, 6) => Tuple
#Unlimited Arguments 2
def add(*args):
sum = 0
for n in args:
sum += n
return sum
print(add(2, 4, 5, 7))
--------------------
18
- Simply change the code to use asterix (*), and then the name of the parameter, ex: *args
- That name args is by convention what most Python developers will use. And it simply stands for arguments. But you don't have to stick with that naming if you don't want to.
- This function add can accept any number of arguments. You can actually loop through all of the arguments which is going to be in the form of a tuple and you can do whatever it is you want with each of those arguments.
- type(*args) ⇒ Tuple
Unlimited (Positional) Arguments
- In addition to looping through it, you can also access them by index because it's a tuple after all.
- The position of your arguments which you pass into the function matters' a huge deal
- This is a way for us to be able to define a function and specify a unlimited or unspecified number of inputs
- The number of arguments for the function can vary because the asterix operator collects all of the arguments into a tuple.
def add(*args):
print(args[1])
add(2, 5, 7, 4)
--------------------
5
Question
def all_aboard(a, *args, **kw):
print(a, args, kw)
all_aboard(4, 7, 3, 0, x=10, y=64)
-----------------------
4 (7, 3, 0) {'x':10, 'y': 64}