Data science encompasses more than just implementing high-level libraries in Python; it also involves grasping the fundamentals and their intermediate aspects. Many aspiring Data Scientists often make the mistake of diving directly into the high-level data science and AI libraries without solidifying their understanding of the language’s basics. That’s why it’s crucial for developers to enhance their grasp of the basic features of any programming language before delving into any specialization. Therefore, this series, “Python: Understanding in 2 minutes,” is tailored for aspiring data scientists aiming to take the “next step” in Python after mastering the basics. We’ll be covering medium-level topics in this series, including positional arguments, args kwargs Python.
This article was published as a part of the Data Science Blogathon
The syntax *args in function definitions is used to pass an array of variables as a function. The program can pass arguments with no keyword or variable length to another. Examples 1 and 2: Python programs showing args for variables of argument length.
Here are the latest Articles of Python in Our Website
This special syntax **kwarg’s function defined by Python uses keyworded variable-length arguments lists. Kwargs are called with two stars. The reason is that double star enables passing keyword arguments. Exemple: A Python program showing Kwargs for variables in keyword argument. Here kwargs can use keyworded variable-length arguments for function calls. First=’Geeks’. Its first key. Geek has values. What is assigned is value and who is assigning it is key.
Arguments (args):
def print_numbers(*args):
for number in args:
print(number)
print_numbers(1, 2, 3, 4)
Keyword Arguments (kwargs):
def greet(**kwargs):
if 'name' in kwargs:
print(f"Hello, {kwargs['name']}!")
else:
print("Hello, there!")
greet(name="Alice")
greet()
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 argskwargs. You can go with anything unless you have the asterisk (*) sign. The asterisk sign basically takes a variable number of Command line arguments.
From the Python documentation on what does ** (double star/asterisk) and * (star/asterisk) do for parameters?
In Python functions, 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). This mechanism is particularly useful for handling multiple arguments efficiently within Python functions.
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 assign to these keyword arguments and Separate Arguments.
Confused? Let’s start with a simple example.
*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
print(sum(1,2,3,4,5))
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.
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 to a Function. 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 and use Following Code
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
Python’s keyword arguments offer flexibility by allowing parameters to be specified by name rather than position. This enhances code readability and enables functions to accept various configurations without strict adherence to parameter order. For instance, a function greet(name, message=”Hello”) can be called as greet(“Alice”) or greet(message=”Hi”, name=”Bob”). Additionally, keyword arguments simplify handling of functions with multiple parameters by explicitly stating each argument’s purpose. This clarity is exemplified in calculate_total_price(price, tax_rate=0.2, discount=0), where values are clearly assigned to parameters. In essence, Python’s keyword arguments empower developers to write more expressive, maintainable, and adaptable code, separating arguments effectively and accommodating extra arguments effortlessly.
ommand line arguments, including single arguments and all the arguments, are parameters provided to a program when executed via the command line or terminal. They modify the program’s behavior without altering its source code. Accessed within the program, arguments can be parsed, including kwargs in Python, to determine actions or parameters. Options or flags (e.g., -h or –help) specify modes or settings, while values represent data for processing. For instance, running a Python program my_program.py –verbose input.txt output.txt sets verbose mode and specifies input and output files. Command line arguments are crucial for configuring program behavior, passing input data, and controlling execution flow. Programs should handle incorrect arguments gracefully, providing helpful error messages or usage instructions.
Do you know why we use arg in functions? It helps with handling variable numbers of arguments. Now, let’s talk about *kwargs, which is another way to handle arguments in a function. It’s similar to args, but it doesn’t take positional arguments. Instead, it accepts keyword arguments. For example, if we have a function called concatenate(), we can use kwargs to go through a dictionary in Python and join its values together. Remember to use (). Here’s how we could rewrite an earlier example using *kwargs: Just keep in mind that in this example, the objects inside the dictionary are typical ones you’d find in a dictionary.”
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.
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/
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.
Great and easy to understand explanation. Thank you
Well written article. And explained in a very simple language. Well done and thank you🙏