Ever wondered what these *varargs or *kwargs in python functions parameter mean? Let me explain!
varargs is short for variable arguments. It is declared like this:
def print_person_varargs(name, *vargs): pass
You can pass as many arguments as you like. In this case we pass two after the first positional argument ‘name:’
print_person_varargs("Jörn", 40, "Emskirchen")
What can you do with it now?
def print_person_varargs(name, *vargs): print(vargs) for arg in vargs: print(arg)
varargs are combined to a tuple. so it is possible to iterate over them
def print_person_kwargs(name, **kwargs): pass
kwargs stands for keyword arguments. you have to pass them as named parameters into a function like this:
print_person_kwargs("Jörn", age=38, city="Emskirchen")
They evaluate to a dictionary so you can iterate as well and access the keys and the values:
def print_person_kwargs(name, **kwargs): print(kwargs) for i, j in kwargs.items(): print(i, j)