
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pass Optional or Keyword Parameters in Python Functions
To pass optional or keyword parameters from one function to another, collect the arguments using the * and ** specifiers in the function's parameter list But, at first, do know what are *args and **args in Python. Let us understand them ?
Variable-length/ Arbitrary arguments in Python (*args)
Example
When you don't know in advance about the number of arguments to be passed, the arguments are variable-length. Include an asterisk i.e. * before the parameter name while defining the function. Let us see an example:
def demo(*car): print("Car 1 = ",car[0]) print("Car 2 = ",car[1]) print("Car 3 = ", car[2]) print("Car 4 = ", car[3]) # call demo("Tesla", "Audi", "BMW", "Toyota")
Output
('Car 1 = ', 'Tesla') ('Car 2 = ', 'Audi') ('Car 3 = ', 'BMW') ('Car 4 = ', 'Toyota')
Arbitrary Keyword Arguments in Python (**kwargs)
When you don't know in advance about the number of keyword arguments to be passed, the arguments are arbitrary keyword arguments.
Example
Let us see an example ?
def demo(**c): print("Car Name: "+c["name"]) print("Car Model: "+c["model"]) # call demo(name = "Tesla", model = "2022")
Output
Car Name: Tesla Car Model: 2022
Pass optional or keyword parameters from one function to another
To pass, collect the arguments using the * and ** in the function's parameter list. Through this, you will get the positional arguments as a tuple and the keyword arguments as a dictionary. Pass these arguments when calling another function by using * and ** ?
def f(a, *args, **kwargs): ... kwargs['width'] = '14.3c' ... g(a, *args, **kwargs)