Interview Kickstart has enabled over 21000 engineers to uplevel.
# What are args and kwargs in Python? Args and kwargs are two parameters used for writing functions in Python. Args stands for arguments, and kwargs stands for keyword arguments. Args are used to pass a non-keyworded, variable-length argument list to a function. Kwargs allow you to pass keyworded, variable-length argument list to a function. In brief, args and kwargs are used to pass a variable number of arguments to a function. ## What are Args? Args are used to pass a non-keyworded, variable-length argument list to a function. This means that you can pass as many arguments as you want to a function, and they will all be stored in a tuple. For example, if you had a function that added two numbers together, you could do this: ``` def add_numbers(*args): total = 0 for a in args: total += a return total print(add_numbers(1,2,3,4)) ``` The output of this code would be 10. The *args allows you to pass in as many numbers as you want, and they will all be added together. ## What are Kwargs? Kwargs are used to pass keyworded, variable-length argument list to a function. This means that you can pass keyworded arguments, and they will all be stored in a dictionary. For example, if you had a function that printed out the details of a person, you could do this: ``` def print_details(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_details(name="John", age=25, city="New York") ``` The output of this code would be: ``` name: John age: 25 city: New York ``` The **kwargs allows you to pass in as many arguments as you want, and they will all be printed out. In conclusion, args and kwargs are two parameters used for writing functions in Python that allow you to pass a variable number of arguments to a function. Args are used to pass a non-keyworded, variable-length argument list to a function, while kwargs are used to pass keyworded, variable-length argument list to a function.
Attend our webinar on
"How to nail your next tech interview" and learn
**args and **kwargs are special keyword arguments in Python, used to pass a variable number of arguments to a function. **args is used to send a non-keyworded variable length argument list to the function. **kwargs allows you to pass keyworded variable length of arguments to a function. Example: def myfunc(*args, **kwargs): for arg in args: print(arg) for key, value in kwargs.items(): print(key + " : " + value) myfunc(1, 2, 3, name="John", age="24") Output: 1 2 3 name : John age : 24