Learn *args and *kwargs in Python: Everything in One Tutorial

Introduction

If you want to shift your coding journey level from basic, or intermediate to an advanced level you need to change the way you write a code a little bit. It takes time. You need to dig more deeply into the programming language you're working with and practice frequently.

To start with the python advanced tutorial, I would like to let you know about *args and *kwargs in python. So, before moving forward, let's find out what actually these things are.

👉 Learn AlsoMulti-threading in Python - Why & Where to Use

What are *args and *kwargs in Python?

Like other programming languages normally python also offers to pass a fixed amount of arguments into a function. But the major difference between python from other languages is that, this rule can be changed in this case.

Python *args and *kwargs allow passing multiple arguments(the number can be anything) to a function. Let's understand it through an example.


def Addition(a, b):
return a+b

print(Addition(5, 3))

See, I passed two integer numbers to the 'Addition()' function. If I send more than two there, the program will give an error message. This problem can be solved by today's topic.

Python *args

*args stands for non-keyword arguments. You can use any name instead of 'args' just need to place the asterisk(*) sign before. Let's see an example.


def Addition(*numbers):
result = 0
for num in numbers:
result += num
return result

print(Addition(5, 3, 9, 5, 4))

See I sent five integer numbers as arguments to the function. In this case, the number of arguments can be anything, and the arguments are passed as a python tuple to the function. Here, '*numbers' is working as an args variable.

Let's try another example to find only the even numbers among many using the python *args.


def Even(*numbers):
evenNums = []
for num in numbers:
if num % 2 == 0:
evenNums.append(num)

return evenNums

print(Even(1, 5, 9, 5, 4, 2, 8, 7, 6))

Python **kwargs

The concept for *kwargs is almost similar to the *args but different in some places. *kwargs stands for keyword arguments that offer to pass multiple numbers of keyword arguments to a function. In this case, arguments are passed as a python dictionary instead of a tuple.

You can use any name instead of 'kwargs', just need to place a double asterisk(**) sign before, to let know the function that it's a 'kwargs' variable. Let's see it through an example.

Code


def Language(**data):
print(f"Data Type: {type(data)}\n")

for key, value in data.items():
print(f"{key}: {value}")

Language(Name="Python", Cur_Version="3.10.4", \
Creator="Guido van Rossum")

Output

Data Type: <class 'dict'>

Name: Python
Cur_Version: 3.10.4
Creator: Guido van Rossum


Since arguments are passed as a python dictionary, we need to use dictionary methods to unpack the data from there. I've used the .items() method here(see the yellow line); you can follow another way to perform this task. Check this article on python dictionary to know, how.

Use *args and **kwargs in the same function

Yes, you can use *args and **kwargs both in the same function, just need to follow the correct order to set these two parameters. Always remember, *args should be placed before **kwargs.

Take this example,

Code


def Language(*text, **data):
line = ''
for word in text:
line += word

print(line)

print(f"\nData Type: {type(data)}\n")

for key, value in data.items():
print(f"{key}: {value}")

Language('I', ' am', ' learning', ' python', \
Name="Python", Cur_Version="3.10.4", Creator="Guido van Rossum")

Output

I am learning python

Data Type: <class 'dict'>

Name: Python
Cur_Version: 3.10.4
Creator: Guido van Rossum


Look, in the above code, I've sent four non-keyword string arguments and then three keyword arguments in one go. If we try to change the ordering of *args and **kwargs there, let's see what happens.

Code


def Language(**data, *text):
line = ''
for word in text:
line += word

print(line)

print(f"\nData Type: {type(data)}\n")

for key, value in data.items():
print(f"{key}: {value}")

Language(Name="Python", Cur_Version="3.10.4", \
Creator="Guido van Rossum", 'I', ' am', ' learning', ' python')

Output

  File "/home/PySeek/Desktop/Programs/args_kwargs/sample2.py", line 1
    def Language(**data, *text):
                         ^
SyntaxError: invalid syntax

 

I hope you get an idea of why this problem happened.

Q & A

Is args a tuple?

Ans: Yes, the arguments are passed as a python tuple, to the *args parameter.

Are args and kwargs considered python keywords?

Ans: Python has a set of reserved words for keywords that cannot be used as variable names, function names, or other identifiers. Currently, there are 35 keywords in the python 3.10.4 version.

If you take any name between 'args' and 'kwargs' as a variable, the program will work perfectly, without any error. Remember, we can not use a keyword name as a variable.

So, the conclusion is, 'args' and 'kwargs' are not python keywords.

Is kwargs a dict?

Ans: Yes, the arguments are passed as a python dictionary, to the **kwargs parameter.

Summary

In this tutorial, we learned everything about python *args and **kwargs and the objectives of this feature. I've tried to explore every single piece of information about this topic here.

I recommend you, write your code with this lovely feature of python whenever it's needed. It'll take you one step closer to writing a code like a professional.

For any query related to this topic please comment below. You'll get an immediate response.

Thanks for reading!💙

PySeek

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post