Default arguments in Python
Last Updated :
11 Sep, 2024
Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value.
Default Arguments:
Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.
Syntax:
def function_name(param1, param2=default_value2, param3=default_value3)
Let’s understand this through a function student. The function student contains 3-arguments out of which 2 arguments are assigned with default values. So, the function student accepts one required argument (firstname), and rest two arguments are optional.
Python
def student(firstname, lastname ='Mark', standard ='Fifth'):
print(firstname, lastname, 'studies in', standard, 'Standard')
We need to keep the following points in mind while calling functions:
- In the case of passing the keyword arguments, the order of arguments is not important.
- There should be only one value for one parameter.
- The passed keyword name should match with the actual keyword name.
- In the case of calling a function containing non-keyword arguments, the order is important.
Example #1: Calling functions without keyword arguments
Python
def student(firstname, lastname ='Mark', standard ='Fifth'):
print(firstname, lastname, 'studies in', standard, 'Standard')
# 1 positional argument
student('John')
# 3 positional arguments
student('John', 'Gates', 'Seventh')
# 2 positional arguments
student('John', 'Gates')
student('John', 'Seventh')
Output:
John Mark studies in Fifth Standard
John Gates studies in Seventh Standard
John Gates studies in Fifth Standard
John Seventh studies in Fifth Standard
In the first call, there is only one required argument and the rest arguments use the default values. In the second call, lastname and standard arguments value is replaced from default value to new passing value. We can see the order of arguments is important from the 2nd, 3rd, and 4th calls of the function.
Example #2: Calling functions with keyword arguments
Python
def student(firstname, lastname ='Mark', standard ='Fifth'):
print(firstname, lastname, 'studies in', standard, 'Standard')
# 1 keyword argument
student(firstname ='John')
# 2 keyword arguments
student(firstname ='John', standard ='Seventh')
# 2 keyword arguments
student(lastname ='Gates', firstname ='John')
Output:
John Mark studies in Fifth Standard
John Mark studies in Seventh Standard
John Gates studies in Fifth Standard
In the first call, there is only one required keyword argument. In the second call, one is a required argument and one is optional(standard), whose value gets replaced from default to a new passing value. In the third call, we can see that order in keyword argument is not important.
Example #3: Some Invalid function calls
Python
def student(firstname, lastname ='Mark', standard ='Fifth'):
print(firstname, lastname, 'studies in', standard, 'Standard')
# required argument missing
student()
# non keyword argument after a keyword argument
student(firstname ='John', 'Seventh')
# unknown keyword argument
student(subject ='Maths')
The above code will throw an error because:
- In the first call, value is not passed for parameter firstname which is the required parameter.
- In the second call, there is a non-keyword argument after a keyword argument.
- In the third call, the passing keyword argument is not matched with the actual keyword name arguments.
Using mutable objects as default argument values in python
This must be done very carefully. The reason is the default values of the arguments are evaluated only once when the control reaches the function
Definition for the first time. After that, the same values(or mutable objects) are referenced in the subsequent function calls.
Things will be much more clear with the example
Python
# mutable default argument values example using python list
# itemName is the name of the item that we want to add to list
# that is being passed, or if it is not passed then appending in
# the default list
def appendItem(itemName, itemList = []):
itemList.append(itemName)
return itemList
print(appendItem('notebook'))
print(appendItem('pencil'))
print(appendItem('eraser'))
Output['notebook']
['notebook', 'pencil']
['notebook', 'pencil', 'eraser']
What you have expected if you assume that a new list is created in each function call when we don’t pass a list to it
[‘notebook’]
[‘pencil’]
[‘eraser’]
But as you can see in the actual output of the program every time the function is called, the same list is used, no new list is made on a new call.
Example using dictionary
Python
# mutable default argument values example using python dictionary
# itemName is the name of item and quantity is the number of such
# items are there
def addItemToDictionary(itemName, quantity, itemList = {}):
itemList[itemName] = quantity
return itemList
print(addItemToDictionary('notebook', 4))
print(addItemToDictionary('pencil', 1))
print(addItemToDictionary('eraser', 1))
Output{'notebook': 4}
{'notebook': 4, 'pencil': 1}
{'notebook': 4, 'pencil': 1, 'eraser': 1} What you have expected if you assume that a new dictionary is created in each function call
{‘notebook’: 4}
{‘pencil’: 1}
{‘eraser’: 1}
But you can clearly see the actual output of the program is different and it indicates the use of the same dictionary in each subsequent call.
The key takeaway here is we should avoid such scenarios.
Best Practices
Assign the default value as none and then check in the function if the expected list or dictionary argument is none or not.
If it is none then assign it with a list or dictionary depending on your requirement.
Python
# using None as values of the default arguments
print('#list')
def appendItem(itemName, itemList=None):
if itemList == None:
itemList = []
itemList.append(itemName)
return itemList
print(appendItem('notebook'))
print(appendItem('pencil'))
print(appendItem('eraser'))
# using None as value of default parameter
print('\n\n#dictionary')
def addItemToDictionary(itemName, quantity, itemList = None):
if itemList == None:
itemList = {}
itemList[itemName] = quantity
return itemList
print(addItemToDictionary('notebook', 4))
print(addItemToDictionary('pencil', 1))
print(addItemToDictionary('eraser', 1))
Output#list
['notebook']
['pencil']
['eraser']
#dictionary
{'notebook': 4}
{'pencil': 1}
{'eraser': 1} Here you can clearly see that every time a function is called and a list or dictionary is not passed as an argument to the function then it creates a new list or dictionary.
Default arguments in Python – FAQs
What is type with 3 arguments in Python?
The type() function with 3 arguments is used to dynamically create a new class. The arguments are:
- Name: The name of the class.
- Bases: A tuple of base classes from which the new class inherits.
- Dict: A dictionary containing the class attributes and methods.
Example:
MyClass = type('MyClass', (object,), {'attr': 5, 'method': lambda self: self.attr})
instance = MyClass()
print(instance.attr) # Output: 5
print(instance.method()) # Output: 5
What are the 4 main data types in Python?
The four main data types in Python are:
int: Integer type for whole numbers.float: Floating-point type for decimal numbers.str: String type for text data.list: List type for ordered, mutable collections of items.
Example:
number = 10 # int
pi = 3.14 # float
name = "Alice" # str
items = [1, 2, 3] # list
What is the default argument in a class method in Python?
The default argument in a class method is typically cls, which refers to the class itself rather than an instance of the class. It allows access to class variables and methods.
Example:
class MyClass:
@classmethod
def class_method(cls):
print(f"Class name: {cls.__name__}")
MyClass.class_method() # Output: Class name: MyClass
What is the default argument pointer?
In Python, there is no explicit “default argument pointer.” However, default arguments in functions or methods allow you to specify a default value for parameters if no value is provided.
Example:
def greet(name="World"):
print(f"Hello, {name}!")
greet() # Output: Hello, World!
greet("Alice") # Output: Hello, Alice!
What’s true about a default argument?
A default argument in Python:
- Can be assigned a value that is used if no argument is provided.
- Must be immutable types like numbers, strings, or tuples; mutable types like lists or dictionaries can lead to unexpected behavior.
- Is evaluated only once when the function is defined, not each time the function is called.
Example:
def append_to_list(element, my_list=[]): # Mutable default argument
my_list.append(element)
return my_list
print(append_to_list(1)) # Output: [1]
print(append_to_list(2)) # Output: [1, 2] # List persists across calls
Similar Reads
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
10 min read
Python def Keyword
Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements indented under a name given using the âdefâ keyword. In Python def
6 min read
Difference between Method and Function in Python
Here, key differences between Method and Function in Python are explained. Java is also an OOP language, but there is no concept of Function in it. But Python has both concept of Method and Function. Python Method Method is called by its name, but it is associated to an object (dependent).A method d
3 min read
First Class functions in Python
First-class function is a concept where functions are treated as first-class citizens. By treating functions as first-class citizens, Python allows you to write more abstract, reusable, and modular code. This means that functions in such languages are treated like any other variable. They can be pas
2 min read
Assign Function to a Variable in Python
In this article, we are going to see how to assign a function to a variable in Python. In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Implementation Simply assign a function to the de
3 min read
User-Defined Functions
Python User defined functions
A function is a set of statements that take inputs, do some specific computation, and produce output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call the function. Functi
7 min read
Python User defined functions
A function is a set of statements that take inputs, do some specific computation, and produce output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call the function. Functi
7 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
3 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
3 min read
Defining a Python function at runtime
In Python,we can define a python function at runtime execute with the help of FunctionType(). First we import types module then perform compile() function and pass parameter exec and after that with the help FunctionType() define the function at runtime. Example 1: Function to print GEEKSFORGEEKS. C
1 min read
Call a function by a String name - Python
In this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between
3 min read
Explicitly define datatype in a Python function
Unlike other languages Java, C++, etc. Python is a strongly, dynamically-typed language in which we don't have to specify the data type of the function's return value and its arguments. It relates types with values instead of names. The only way to specify data of specific types is by providing expl
3 min read
Built-in and Special Functions
Global and Local Variables
Global keyword in Python
In this article, we will cover the global keyword, the basic rules for global keywords in Python, the difference between the local, and global variables, and examples of global keywords in Python. What is the purpose of global keywords in python? A global keyword is a keyword that allows a user to m
5 min read
Python Scope of Variables
In Python, variables are the containers for storing data values. Unlike other languages like C/C++/JAVA, Python is not âstatically typedâ. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. Python Scope variabl
5 min read
Accessing Python Function Variable Outside the Function
In Python, variables defined within a function have local scope by default. But to Access function variables outside the function usually requires the use of the global keyword, but can we do it without using Global. In this article, we will see how to access a function variable outside the function
4 min read
Return Statements
How to pass optional parameters to a function in Python?
In Python, when we define functions with default values for certain parameters, it is said to have its arguments set as an option for the user. Users can either pass their values or can pretend the function to use theirs default values which are specified. In this way, the user can call the function
5 min read
Returning Multiple Values in Python
In Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. Python Code # A Python program to return multiple # values from a
4 min read
Python None Keyword
None is used to define a null value or Null object in Python. It is not the same as an empty string, a False, or a zero. It is a data type of the class NoneType object. None in Python Python None is the function returns when there are no return statements. C/C++ Code def check_return(): pass print(c
2 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store
4 min read