business, cellphone, codes

*args and **kwargs

In Python, you can use *args and **kwargs to accept a variable amount of parameters in a functions call.

*args will accept unlimited values as a Tuple.

def foo(*args):
    for arg in args:
        print(arg)

foo(1,2,3)

# will result in
# 1
# 2
# 3

**kwargs will accept key pair values as a dictionary.

def foo(**kwargs):
    for kwarg in kwargs:
        print(kwarg)
        print(kwargs[kwarg])

foo(value1=1,value2=2)

# will result in
# value1
# 1
# value2
# 2

Note that the text, args or kwargs, is not important and can be replaced with any other text. It is the asterisk * for tuple and double asterisk ** for dictionary that is important.

def foo(*a): #tuple
  ...

def foo(**a): #dict
  ...

Similar Posts

Leave a Reply

Your email address will not be published.