Function Arguments and its Types in Python

In this Python article, we will discuss the arguments which we can send in the function along with its different types with some interesting examples.

1. What is an Argument to a function?

We all must have heard the word Parameters and Arguments. Did we ever wonder what is the difference between them? If we observe from a function’s perspective:

A parameter for a function definition can be defined as the variable listed inside the parentheses in the function definition.

Whereas, an argument for a function definition can be defined as the value that is sent to the function when it is called.

Difference between arguments & functions

When we define our function or use the in-built function there may be a need to pass arguments to pass some values to be used in the function’s body.

We pass different data to the function so that no two functions will have the same invocation unless required. Let’s understand better with a small example.

def engine(process, state):
    print( process + ', ' + state)

engine("Computation", "Machine up and running")
Output
Computation, Machine up and running

Here, in the above example, we passed two arguments, and hence the function is working fine. But, if we passed only one argument, the interpreter will show an error message. Let’s check how the exception is thrown if we use wrong number of arguments.

def engine(process, state):
    print(process + ', ' + state)

engine("Computation")
Output
Traceback (most recent call last):
   File "", line 1, in 
 TypeError: engine() missing 1 required positional argument: 'state'

2. How do Positional Arguments work in python?

In python, the simplest way to pass arguments in a function is with positional arguments or required arguments. In this type of function definition, we just need to specify the parameters inside the parentheses separated by commas.

NOTE: We can regard the Positional argument as the simplest way, but there is one point to be considered. The same number of arguments with the same order must be maintained in the function call according to defined parameters in the definition.

def coder(task, output):
    print(task, output)

coder("Coding", "No error(Successful)")
Output
Coding No error(Successful)

The simplest way yet positional argument afford the least flexibility. It means that the call order of the arguments must match the order of the parameter in the definition.

Although we may pass the positional arguments out of order, they may not produce the correct result. As a programmer, we must state what the appropriate arguments should be, and the user should be aware of that information of the function and stick to it.


3. How do Arbitrary Arguments work in python?

As a programmer, sometimes we do not know that how many numbers of arguments will be passed into a function. So, we can handle such conditions by calling the function with arbitrary arguments.

The asterisk mark before the parameter name signifies arbitrary input in the function definition. Let’s take an example to understand better.

def tasks(*tsk):
    for i in tsk:
        print(i)

tasks("Learning", "Eating", "Sleeping", "Running")
Output
Learning
Eating
Sleeping
Running

The arguments we pass get stored or wrapped in a tuple before they are been passed to the function. Then in the implementation above we use for loop to retrieve the arguments from the tuple one by one.

3.1. Arbitrary arguments in combination with other arguments

We can combine the arbitrary arguments with other arguments, but there is one certain rule to follow i.e. parameter with * should be the last parameter of the method definition.

Note: It will assign arguments by their position and all the remaining values to the last arbitrary argument.

Let’s implement an example to show the usage.

def tasks(a, b, *c):
  print(type(a), a)
  print(type(b), b)
  print(type(c), c)


tasks("Learning", 1, 2, "Running")
Output
Learning
1
(2, 'Running')

Note: If there is any other parameter defined after the parameter with * then it will throw an error.

Let’s implement an example to see the error.

def tasks(a, *c, b):
  """
  this will throw error
  """

tasks("Learning", 1, 2, "Running")
Output
Traceback (most recent call last):
   File "/Users/hiteshgarg/IdeaProjects/personal/codingeek/Python/./test.py", line 15, in 
     tasks("Learning", 1, 2, "Running")
TypeError: tasks() missing 1 required keyword-only argument: 'b'

4. How do Default Arguments work in Python?

There may be many cases where we want to give default input. This is generally used to simplify the code as we do not have to pass that parameter again and again when we want to use the default value.

In python, we can pass the default value by using the assignment operator.

def engine(process, state="Undefined"):
  print(process + ', ' + state)


engine("Computation")
engine("Computed", "Engine off")
Output
Computation, Undefined
Computed, Engine off

Here, in the above example, we have set a default value to the state so that if the argument is not passed, it will still have some value and it will not give out any error.

On the other hand, when value is provided as an argument then it overwrites the default value.

We may make any number of arguments as default but if we have made the argument default then all the arguments to their right must have default values. In short, default arguments cannot lead the non-default arguments.

def engine(state="Undefined", process):
  print(process + ', ' + state)


engine("Computation")
Output
SyntaxError: non-default argument follows default argument 

5. How do Keyword Arguments work in Python?

Till now we have observed that whenever we call a function, we give some values to it which gets assigned to the arguments according to their respective position.

For example, engine("computed,"Engine off") the value "computed" was assigned to the argument process and similarly "Engine off" to state.

In python, we may call the function with different argument positions. Let’s see some examples to understand how it works.

def engine(process, state="Undefined"):
  print(process + ', ' + state)


engine(process="Computation")
engine(state="Engine off", process="Computed")
Output
Computation, Undefined
Computed, Engine off

Same as the positional arguments, keyword arguments also have a condition to follow, we cannot put positional arguments after keyword arguments.

def engine(process, state):
  print(process + ', ' + state)


engine(state="Engine off", "Computed")
Output
SyntaxError: postional argument follows keyword argument

6. Ways to Pass values in Function

Generally, in most programming languages, we have two commonly used paradigms to pass arguments to a function.

  • Pass-by-value: In this method, a copy of the argument is passed to the function rather than actual arguments. It means that any change in the copy arguments will not affect the actual values.
  • Pass-by-reference: In this method, we pass the reference to the argument in the function. Here, the actual value will be affected.
n = 2
n = 4

Here, in the above example,

  • The first line assigns n variable to an object with value 2
  • The second line assigns an object with value 4 to n which means that n is reassigned to an object which has a value of 4
def val(x):
  x = 20
  print("Value of x => ", x)

n = 5
val(n)
print("Value of n => ", n)
Output
Value of x =>  20
Value of n =>  5

In the above program, the value of n was assigned to an object with a value of 5. Initially, x had the value 5 but the function’s 2nd line rebinds it to a new object with value 20 but the variable n is still unaffected as we have assigned a new object to x and it has lost the reference to the old object with value 5.

We can say that in python, the argument passing is overall a hybrid mixture of both pass-by-reference and pass-by-value. As the object is sent to the function in a reference way, but the reference is passed by value.

One important thing that we should remember is that in Python, we call the passing of arguments mechanism the pass-by-assignment.

It is called so because parameter names get bound to objects as the function enters, and same as we know assignment is also the process of attaching a name to an object. We may also see some more terms like pass-by-object, pass-by-object-reference, or pass-by-sharing.

def f(value):
  value[1] = '###'


list1 = ['abc', 'def', 'ghi', 'jkl']
f(list1)
print(list1)
Output
['abc', '###', 'ghi', 'jkl']

In the above example, we can see the argument passed to f() is a list. When we call f(), a reference list1 is passed. If we assign value to anything else, then it may have been bound to a different object, and the link to list1 would have been lost.

However, the function f() can use the reference for any modification inside list1. We can clearly see that after the function updates the list1, and the same changes are reflected in the calling environment.

Momentarily, if in a function we are Passing an immutable object, like an intstr, or tuple. it will act like a pass-by-value. While calling, the function would not be allowed to modify the object.

If in a function we are Passing a mutable object, like a listdict, or set acts partially like pass-by-reference. While calling, the function will be allowed to change items in place within the object and these changes will be visible to the user.


7. Conclusion

In this article we learned everything about the arguments in Python

  • What is an argument to a function in python and its examples.
  • How do Positional argument, arbitary argument, default argument, and keyword argument work along with the suitable examples.
  • Different ways to pass value to a function Pass-by-value and Pass-by-reference.

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x