+ 1
*args and *kwargs
Please if someone can tell me for what is used *args and for what *kwargs in Python. I'm confused. ...Sorry for my bad English...
4 Answers
+ 7
Parameters without * are standard parameters. They need to be provided when the function is called.
Parameters with * are optional parameters. They can be omitted. If you provide them, they will be stored in a tuple.
Parameters with ** are keyword parameters. They can be omitted. If you provide them, they will be stored in a dictionary.
Example:
def func(a, b, *c, **d):
print(a)
print(b)
print(c)
print(d)
func() expects at least two arguments, a and b. If you provide more arguments, they will be stored in the tuple c, keyword arguments in the dict d.
func(1) # error: func() expects at least two arguments (a and b)
func(1, 2) # output: 1, 2, (), {} <= no optional argument c (empty tuple), no keyword argument (empty dict)
func(1, 2, 3) # 1, 2, (3, ), {} <= optional argument c is stored in a tuple, no keyword arguments (empty dict)
func(1, 2, 3, 4, 5, 6, 7) # 1, 2, (3, 4, 5, 6, 7), {} <= 3-7 are all optional arguments, all stored in a tuple, no keyword arguments (empty dict)
func(1, 2, 3, 4, k=9, m=10) # a = 1, b = 2, c = (3, 4), d = {'k': 9, 'm': 10}
+ 9
k stand for key. Read more here https://pythontips.com/2013/08/04/args-and-kwargs-in-JUMP_LINK__&&__python__&&__JUMP_LINK-explained/
+ 2
Anna thanks so much đ
0
Hubert Dudek thanks