Args and kwargs provide a way to pass multiple function arguments. This way we can make a general purpose function which can take variable number of arguments.
Args
We can pass multiple values to a function and perform operations on those values using *args.
Let’s say you want to define a add function that can take variable number of arguments and it will return the sum of all the values as its output. These kinds of functionality can be achieved using *args variables.
This args variable holds the passed arguments in the form of a tuple as shown in the code below.
1def add(*args):
2 print(args)
3add(2,3) # (2, 3)
Once we have this tuple, we can extract individual elements by iterating through this tuple object.
Example:
1def add(*args):
2 sum = 0
3 for num in args:
4 sum += num
5 return sum
6
7print(add(2,3)) # 5
8print(add(1,2,3)) # 6
9print(add(1,2,3,4)) # 10
If we want to pass other arguments other than args, we can pass them before the args variable. If our function is accepting multiple parameters, then other named arguments should come before args variable.
Example:
1def calculate(*args, department):
2 sum = 0
3 for num in args:
4 sum += num
5
6 print(f"Department {department}: {sum}")
Output:
TypeError: calculate() missing 1 required keyword-only argument: 'department
The department argument should come before *args.
It’s a common convention to name this variable argument variable as args in Python but we can name it whatever we wish.
1def calculate(department, *args):
2 sum = 0
3 for num in args:
4 sum += num
5 print(f"Department {department}: {sum}")
6
7calculate("Finance", 2, 3, 4) # Department Finance: 9
Kwargs
**kwargs are similar concept to *args in that we can have parameters in the form of keyword arguments. These arguments will be available as a dictionary object with variable name as the keys.
1def sample_kwargs(**kwargs):
2 print(kwargs)
3sample_kwargs(name="Andrew", age=22) # {'name': 'Andrew', 'age': 22}
You can see that the arguments are passed as keyword arguments and they are available in dictionary named kwargs. It is common convention in Python community to name this variable as kwargs.
Example:
1def sample_kwargs(**kwargs):
2 for key,value in kwargs.items():
3 print("{0} : {1}".format(key, value))
4sample_kwargs(name="Andrew", age=22)
Output:
name : Andrew
age : 22
Additional Python Functions
There are few additional functions available in Python which can become quite useful.
abs()function is used to find absolute value of a number. If the number is negative, this function returns the positive number for the same negative number. If the number was positive, it will not change anything.
1number = -10
2print(abs(number)) # 10
3number = -2.5
4print(abs(number)) # 2.5
all()functio ncan be used to check if all members of a collection data type are truthy or falsy values. In Python, some values are not exactlyFalsebut in conditional check, they behave like aFalse, so they are considered falsy values. These values includeNone,False,0as well as empty string.
1numbers = [1, 2, 3]
2print(all(numbers)) # True
3numbers = [0, 1, 2, 3]
4print(all(numbers)) # False
5items = [None, True, "hello"]
6print(all(items)) # False
- Similarly,
any()function can be used to check if any of the value is truthy.
1items = [0, "", False]
2print(any(items)) # False
3items = [0, "", True]
4print(any(items)) # True
divmod()function returns the quotient and remainder of the division operation as a tuple.
1quotient, remainder = divmod(5, 2)
2print(quotient, remainder) # 2 1
isinstance()method can be used to check if an object is an instance of specific class.
1name = "Victoria"
2print(isinstance(name, str)) # True
- We can use
min(),max()andsum()functions to find minimum, maximum and sum of all numbers from a list of numbers. If one of the element contains other data type, it will try to cast that value into numerical datatype. If it cannot be cast to number type, then it throws an error.
1numbers = [1, 2, 3]
2print("Min:", min(numbers)) # Min: 1
3print("Max:", max(numbers)) # Max: 3
4print("Sum:", sum(numbers)) # Sum: 6


Comments