Akash — July 10, 2021
Beginner Programming Python

This article was published as a part of the Data Science Blogathon

Introduction

Data science is not only about implementing high-level libraries in Python, but also about understanding the fundamentals and their intermediate aspects. Most often, the aspiring Data Scientist makes a mistake by diving directly into the high-level data science and AI libraries instead of solidifying the basics of the language. That’s why it is crucial for the developers to enhance the basic features of any programming language before jumping into any specialization. Therefore, this series of Python: Understanding in 2 minutes is dedicated to aspiring data scientists who want to take the “next step” in Python after learning the basics. We shall cover the medium-level topics in this series. In this tutorial, the represents arguments and keyword arguments in Python.

What exactly are **args and **kwargs?

python *args and **kwargs

Let’s start by understanding what *args and **kwargs represent in Python.

You must have frequently seen such things in Python.

def function_name(*args, *kwargs):
    # body

Confused with these notations? Don’t worry. We all have been there.

First of all, let’s begin by understanding that it is not mandatory to write the words args and kwargs. You can go with anything unless you have the asterisk (*) sign. The asterisk sign basically takes a variable number of arguments.

The official doc’s saying

From the Python documentation on what does ** (double star/asterisk) and * (star/asterisk) do for parameters?

If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax “*identifier” is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).

If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax “**identifier” is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.

Confused? Let’s start with a simple example.

What is *args doing?

*args allows you to pass the desired number of arguments to the function. Args generally means arguments in this case. Let’s see an example.

def demo(*args):
    print(args)

Call the function

demo("Humpty", "Dumpty") # call with two arguments

Output:

('Humpty', 'Dumpty')

Call the function again, this time with 6 arguments

demo("Humpty", "Dumpty", "Sat", "On", "A", "Wall") # call with two arguments

Thus, regardless of the number of arguments passed, *args is showing you the result. Doesn’t matter if you pass (“Humpty”, “Dumpty”) or (“Humpty”, “Dumpty”, “Sat”, “On”, “A”, “Wall”). , *args will handle that for you. Note: As mentioned, you can write anything and not just args. Let’s try *whatever.

def demo(*whatever):
    print(whatever)

Call the function

demo("Humpty", "Dumpty", "Sat", "On", "The", "Wall")

Output:

('Humpty', 'Dumpty', 'Sat', 'On', 'The', 'Wall')

And that’s perfectly fine!

Let’s write a function that sums up as many inputs as we want.

def sum(*args):
    c = 0
    for arg in args:
        c+=arg
    return c

Call the function

sum(1,2,3,4,5)

Output:

15

Call again. This time with more arguments.

sum(1,2,3,4,5,6,7,8,9,10)

Output:

55

Doesn’t matter if you sum 1 to 5 or 1 to 10, Python will calculate the result for you irrespective of the number of parameters. This is the beauty of *args.

The case with **kwargs

Now, what about **kwargs? Well, they are not much different. The term Kwargs generally represents keyword arguments, suggesting that this format uses keyword-based Python dictionaries. Let’s try an example.

def demo(**kwargs):
    print(kwargs)

Call the function

demo(name="Humpty", location="Wall")

Output:

{'name': 'Humpty', 'location': 'Wall'}

**kwargs stands for keyword arguments. The only difference from args is that it uses keywords and returns the values in the form of a dictionary. Now, let’s write a normal function and pass arguments through args and kwargs.

def list_numbers(first, second, third):
    print("First number", first)
    print("Second number", second)
    print("Third number", third)

Call the function

args = ("One","Two","Three")
list_numbers(*args)

Output:

First number One
Second number Two
Third number Three

Another shot!

kwargs = {"third": "Three", "second": "Two", "first": "One"}
list_numbers(**kwargs)

Output:

First number One
Second number Two
Third number Three

Conclusion:

conclusion | python *args and **kwargs
Image: Chris Ried on Unsplash

So, we wrap up the first tutorial under the series Python: Understanding in 2 minutes. The idea is to walk through the intermediate and advance concepts of Python in order to become an efficient Python developer before becoming an efficient Data Scientist. It’s true that Python’s learning curve is easy and the syntactical features of Python are rather simple and easy to understand. But, many beginners wonder “what’s next” after learning the basics. Therefore, in this series, we are covering those intermediate aspects of Python. The topics include Args and Kwargs, Generators, Map, Reduce, Filter, Sets, Decorators, Threading, __slot__, Collections, Enumerate, Object Inspection, Comprehensions, Exceptions, OOP(Object Oriented Python), etc. We will cover each of these intermediate sections one by one in the upcoming posts.

About the Author:

Hi there! My name is Akash and I’ve been working as a Python developer for over 4 years now. In the course of my career, I began as a Junior Python Developer at Nepal’s biggest Job portal site. Later, I was involved in Data Science and research at Nepal’s first ride-sharing company, Tootle. Currently, I’ve been actively involved in Data Science as well as Web Development with Django.

You can find my other projects on:

https://github.com/akashadhikari

Connect me on LinkedIn

https://www.linkedin.com/in/akashadh/

Email: [email protected] | [email protected]

Website (Working on The Data Science Blog): https://akashadhikari.github.io/

End Notes:

Thanks for reading!

I hope enjoyed reading the article. If you found it useful, please share it among your friends on social media too. For any queries, suggestions, constructive criticisms, or any other discussion, please ping me here in the comments or you can directly reach me through email.

I am also planning to start The Data Science Blog on my Github page. I will try to include how real companies have been working in the field of Data Science, how to excel in Data Science and/or tech interviews, and other useful content related to Python and general programming. Feel free to check them once in a while.

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

About the Author

Our Top Authors

  • Analytics Vidhya
  • Guest Blog
  • Tavish Srivastava
  • Aishwarya Singh
  • Aniruddha Bhandari
  • Abhishek Sharma
  • Aarshay Jain

Download Analytics Vidhya App for the Latest blog/Article

Leave a Reply Your email address will not be published. Required fields are marked *