The Wayback Machine - http://web.archive.org/web/20240930185732/https://www.geeksforgeeks.org/default-arguments-in-python/
Open In App

Default arguments in Python

Last Updated : 11 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: 

  1. In the case of passing the keyword arguments, the order of arguments is not important.
  2. There should be only one value for one parameter.
  3. The passed keyword name should match with the actual keyword name.
  4. 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:

  1. Name: The name of the class.
  2. Bases: A tuple of base classes from which the new class inherits.
  3. 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:

  1. int: Integer type for whole numbers.
  2. float: Floating-point type for decimal numbers.
  3. str: String type for text data.
  4. 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


    Previous Article
    Next Article

    Similar Reads

    Python | Set 6 (Command Line and Variable Arguments)
    Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers]. There is another method that uses command line arg
    2 min read
    Python | Passing dictionary as keyword arguments
    Many times while working with Python dictionaries, due to advent of OOP Paradigm, Modularity is focussed in different facets of programming. Hence there can be many use cases in which we require to pass a dictionary as argument to a function. But this required the unpacking of dictionary keys as arguments and it's values as argument values. Let's d
    3 min read
    Python: Passing Dictionary as Arguments to Function
    A dictionary in Python is a collection of data which is unordered and mutable. Unlike, numeric indices used by lists, a dictionary uses the key as an index for a specific value. It can be used to store unrelated data types but data that is related as a real-world entity. The keys themselves are employed for using a specific value. Refer to the belo
    2 min read
    Tuple as function arguments in Python
    Tuples have many applications in all the domains of Python programming. They are immutable and hence are important containers to ensure read-only access, or keeping elements persistent for more time. Usually, they can be used to pass to functions and can have different kinds of behavior. Different cases can arise. Case 1: fnc(a, b) - Sends a and b
    2 min read
    Python - pass multiple arguments to map function
    The map() function is a built-in function in Python, which applies a given function to each item of iterable (like list, tuple etc.) and returns a list of results or map object. Syntax : map( function, iterable ) Parameters : function: The function which is going to execute for each iterableiterable: A sequence or collection of iterable objects whi
    3 min read
    Executing functions with multiple arguments at a terminal in Python
    Commandline arguments are arguments provided by the user at runtime and gets executed by the functions or methods in the program. Python provides multiple ways to deal with these types of arguments. The three most common are: Using sys.argv Using getopt module/li> Using argparse module The Python sys module allows access to command-line argument
    4 min read
    How to handle invalid arguments with argparse in Python?
    Argparse module provides facilities to improve the command-line interface. The methods associated with this module makes it easy to code for command-line interface programs as well as the interaction better. This module automatically generates help messages and raises an error when inappropriate arguments are passed. It even allows customizing the
    4 min read
    Unpacking arguments in Python
    If you have used Python even for a few days now, you probably know about unpacking tuples. Well for starter, you can unpack tuples or lists to separate variables but that not it. There is a lot more to unpack in Python. Unpacking without storing the values: You might encounter a situation where you might not need all the values from a tuple but you
    3 min read
    Pass function and arguments from node.js to Python
    Prerequisites: How to run python scripts in node.js using the child_process module. In this article, we are going to learn how to pass functions and arguments from node.js to Python using child_process. Although Node.js is one of the most widely used web development frameworks, it lacks machine learning, deep learning, and artificial intelligence l
    4 min read
    Pass Arguments to the Metaclass from the Class in Python
    Metaclasses in Python provide a powerful way to control the creation and behavior of classes. They act as the "class of a class" and allow you to customize class creation and behavior at a higher level. One interesting aspect of metaclasses is the ability to pass arguments from a class to its metaclass during the class definition. What is a Metacla
    3 min read
    Command Line Arguments in Python
    The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. The three most common are:  Using sys.argvUsing getopt moduleUsing argparse moduleUsing sys.argvThe sys module provides functions and
    5 min read
    Deep dive into Parameters and Arguments in Python
    There is always a little confusion among budding developers between a parameter and an argument, this article focuses to clarify the difference between them and help you to use them effectively. Parameters:A parameter is the variable defined within the parentheses during function definition. Simply they are written when we declare a function. Examp
    3 min read
    How to Print Multiple Arguments in Python?
    An argument is a value that is passed within a function when it is called.They are independent items, or variables, that contain data or codes. During the time of call each argument is always assigned to the parameter in the function definition. Example: Simple argument [GFGTABS] Python def GFG(name, num): print("Hello from ", name +
    3 min read
    How to find the number of arguments in a Python function?
    In this article, we are going to see how to count the number of arguments of a function in Python. We will use the special syntax called *args that is used in the function definition of python. Syntax *args allow us to pass a variable number of arguments to a function. We will use len() function or method in *args in order to count the number of ar
    3 min read
    How to bind arguments to given values in Python functions?
    In Python, binding arguments to specific values can be a powerful tool, allowing you to set default values for function parameters, create specialized versions of functions, or partially apply a function to a set of arguments. This technique is commonly known as "partial function application" and can be achieved using Python's functools.partial as
    3 min read
    Packing and Unpacking Arguments in Python
    We use two operators * (for tuples) and ** (for dictionaries). Background Consider a situation where we have a function that receives four arguments. We want to make a call to this function and we have a list of size 4 with us that has all arguments for the function. If we simply pass a list to the function, the call doesn't work. [GFGTABS] Python
    5 min read
    Can Named Arguments Be Used with Python Enums?
    Enums (Enumerations) are a symbolic representation of a set of named values, commonly used in programming to define a collection of constants. In Python, Enums are used to organize sets of related constants in a more readable and maintainable way. Using named arguments with enums can enhance clarity and functionality by allowing us to associate add
    3 min read
    Core arguments in serializer fields - Django REST Framework
    Serializer fields in Django are same as Django Form fields and Django model fields and thus require certain arguments to manipulate the behaviour of those Fields. In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. This article revolves around various arguments that serializer
    6 min read
    Functions that accept variable length key value pair as arguments
    To pass a variable-length key-value pair as an argument to a function, Python provides a feature called **kwargs.kwargs stands for Keyword arguments. It proves to be an efficient solution when one wants to deal with named arguments in their function. Syntax: def functionName(**anything): statement(s) Note: adding '**' to any term makes it a kwargs
    2 min read
    How to Pass Arguments to Tkinter Button Command?
    When a user hits the button on the Tkinter Button widget, the command option is activated. In some situations, it's necessary to supply parameters to the connected command function. In this case, the procedures for both approaches are identical; the only thing that has to vary is the order in which you use them. Method 1: Pass Arguments to Tkinter
    2 min read
    How to pass arguments to shell script in crontab ?
    In this article, we will discuss how to schedule shell scripts in crontab and to pass necessary parameters as well. First, let's create a simple script that we will be scheduled to run every 2 minutes. The below is a simple script that calculates the sum of all parameters passed and prints them to STDOUT along with the time the script was run. #! /
    2 min read
    Passing URL Arguments in Flask
    In this article, we will cover how to Pass URL Arguments in Flask using Python. URL converters in Flask are mentioned in angular brackets (<>). These unique converters are designed to let us generate extremely dynamic URLs, where a part of the URL is regarded as a variable. For that we have created three different endpoints to understand thre
    4 min read
    How to pass multiple arguments to function ?
    A Routine is a named group of instructions performing some tasks. A routine can always be invoked as well as called multiple times as required in a given program.  When the routine stops, the execution immediately returns to the stage from which the routine was called. Such routines may be predefined in the programming language or designed or imple
    5 min read
    Get the number of Explicit Arguments in the Init of a Class
    In Python, the __init__ method is used for initializing a newly created object. It typically contains parameters that set the initial state of an object. To count the number of explicit arguments in the __init__ method of a class, we can use the inspect module from Python's standard library. In this article, we will see how we can get the number of
    3 min read
    Python IMDbPY – Default info of Company object
    In this article we will see how we can achieve the set of information which retrieved by default by get_company method, with the help of get_company_infoset we can know all the information that we can achieve of the company. But all the information is not extracted as it will be time consuming process. In order to know the default information that
    1 min read
    Python IMDbPY – Default info of Movie object
    In this article we will see how we can achieve the set of information which retrieved by default by get_movie method, with the help of get_movie_infoset we can know all the information that we can achieve of the movie. But all the information is not extracted as it will be time consuming process. In order to know the default information that a movi
    1 min read
    Python IMDbPY – Default info of Person object
    In this article we will see how we can achieve the set of information which retrieved by default by get_person method, with the help of get_person_infoset we can know all the information that we can achieve of the person. But all the information is not extracted as it will be time consuming process. In order to know the default information that a m
    1 min read
    Use mutable default value as an argument in Python
    Python lets you set default values ​​for its parameters when you define a function or method. If no argument for this parameter is passed to the function while calling it in such situations default value will be used. If the default values ​​are mutable or modifiable (lists, dictionaries, etc.), they can be modified within the function and those mo
    5 min read
    Least Astonishment and the Mutable Default Argument in Python
    The principle of Least Astonishment (also known as least surprise) is a design guideline that states that a system should behave the way it is intended to behave. It should not change its behavior in an unexpected manner to astonish the user. By following this principle, designers can help to create user interfaces that are more user-friendly and l
    3 min read
    Why Python Uses 'Self' as Default Argument
    Python, a versatile and widely used programming language, follows object-oriented principles in its design. One of the distinctive features of Python is the use of the keyword 'self' as a default argument in class methods. This choice plays a crucial role in maintaining the integrity of object-oriented programming (OOP) concepts and ensures proper
    3 min read
    Article Tags :
    Practice Tags :