Python: *args and **kwargs

A simple working example and a link to the official documentation

example

# using *args and **kwargs in functions
# 2018/10/24
# Official documentation: https://docs.python.org/2/tutorial/controlflow.html#more-on-defining-functions

# Python Bits & Pieces
# Stefan Gaillot
# xenjee@gmail.com


def args_and_kwargs(my_var, *args, **kwargs):
    print "a variable has been passed, received as 'my_var':", my_var
    print "args (tuple): ", args
    print "args[0]: ", args[0]
    print "args[1]: ", args[1]
    for arg in args:
        print arg
    # print "-" * 40
    keys = sorted(kwargs.keys())
    for kw in keys:
        print kw, ":", kwargs[kw]


args_and_kwargs("my_variable", "this is arg1", "this is arg2", key01='value 01', key02="value 02", key03="value 03")

print '-' * 40

args_and_kwargs(2, "second_arg", "third_arg")

Leave a Reply