Python: function var-positional parameter (rest param) (*x)
Var-positional parameter
To define unspecified number of positional parameters, use
*x
The function receive it as a Tuple.
for example
def ff(*x):
def ff(a,b,*x):
🟢 tip: this is useful if you need to define a function such as sum.
you can have more parameters after it. but any parameter after it is for keyword parameter only. that is, in function call, it must give arg by the keyword form name=val.
the terminology for the *x is var-positional parameter.
It means, it eats all positional arguments in function call at that position.
in most other programing languages, it's called rest parameter.
It's not called rest parameter in python because in python there can be keyword parameters after it.
# function with unspecified number of positional args def ff(*x): # x is received as a tuple. return x rr = ff(5,6) print(rr) # (5, 6) print(type(rr)) # <class 'tuple'>
Example. position params with star-args
# example of position param with rest param def ff(a, *x): return [a, x] rr = ff(5, 6, 7) print(rr == [5, (6, 7)]) # [5, (6, 7)]
Example. rest param followed by keyword only param
# example of rest param followed by a keyword parameter def ff(*x, aa=1): return [x, aa] rr = ff(5, 6, 7) print(rr) # [(5, 6, 7), 1] # the parameter aa didn't get value from the function call. it uses default value. # because in the function call, no keyword arg is given.
# example of rest param followed by a positional param def ff(*x, aa): return [x, aa] rr = ff(5, 6, 7, aa=1) print(rr) # [(5, 6, 7), 1] # aa gets value 1 from the function call.