Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Ashutosh Krishna
Ashutosh Krishna

Posted on • Originally published atireadblog.com on

*args and **kwargs in Python

Introduction

In this article, we'll discuss*args and**kwargs in Python with their uses and examples.

When writing a function, we often need to pass values to the function. These values are calledfunction arguments.

Problem with Function Arguments

Let us define a function to add two numbers in Python. We'll write it as:

defadd(x,y):returnx+yprint(add(2,3))
Enter fullscreen modeExit fullscreen mode

Output:

5
Enter fullscreen modeExit fullscreen mode

What if further it is required to add three numbers? Simple, we can modify the function to accept three arguments and return their sum as:

defadd(x,y,z):returnx+y+zprint(add(2,3,5))
Enter fullscreen modeExit fullscreen mode

Output:

10
Enter fullscreen modeExit fullscreen mode

Wasn't that quite simple? Yes, it was!

But what if we're again required to add two numbers only? Will our modified function help us get the sum? Let's see:

defadd(x,y,z):returnx+y+zprint(add(2,3))
Enter fullscreen modeExit fullscreen mode

Output:

Traceback(most recent call last):  File"D:\Quarantine\Test\Blog-Codes\args-kwargs\main.py", line 14,in <module>    print(add(2, 3))TypeError: add() missing 1 required positional argument:'z'
Enter fullscreen modeExit fullscreen mode

You see the problem?

The problem arises when we have a variable number of arguments. Shall we keep modifying the function to accept the exact number of arguments? Of course not, we won't be doing this.

Thus, there must be some other way to do it. This is where*args and**kwargs jump in!

*args and**kwargs are used as arguments of a function when we are unsure about the number of arguments to pass in the functions.

*args in Python

*args allows us to pass a variable number of non-keyword arguments to a Python function. In the function, we should use an asterisk(* ) before the parameter name to pass a variable number of arguments.

defadd(*args):print(args,type(args))add(2,3)
Enter fullscreen modeExit fullscreen mode

Output:

(2, 3) <class'tuple'>
Enter fullscreen modeExit fullscreen mode

Thus, we're sure that these passed arguments make a tuple inside the function with the same name as the parameter excluding*.

Now let us rewrite ouradd() function with a variable number of arguments.

defadd(*numbers):total=0fornuminnumbers:total+=numreturntotalprint(add(2,3))print(add(2,3,5))print(add(2,3,5,7))print(add(2,3,5,7,9))
Enter fullscreen modeExit fullscreen mode

Output:

5101726
Enter fullscreen modeExit fullscreen mode

Note that the name of the argument need not necessarily beargs, it can be anything, in this case, it'snumbers. But it's generally a standard way to use*args as the name.

**kwargs** in Python**

** kwargs allows us to pass a variable number of keyword arguments to a Python function. In the function, we use the double-asterisk (** )before the parameter name to denote this type of argument.

deftotal_fruits(**kwargs):print(kwargs,type(kwargs))total_fruits(banana=5,mango=7,apple=8)
Enter fullscreen modeExit fullscreen mode

Output:

{'banana': 5,'mango': 7,'apple': 8} <class'dict'>
Enter fullscreen modeExit fullscreen mode

Thus we see that the arguments, in this case, are passed as adictionary and these arguments make a dictionary inside the function with name same as the parameter excluding**.

Now, let us complete thetotal_fruits() function to return the total number of fruits.

deftotal_fruits(**fruits):total=0foramountinfruits.values():total+=amountreturntotalprint(total_fruits(banana=5,mango=7,apple=8))print(total_fruits(banana=5,mango=7,apple=8,oranges=10))print(total_fruits(banana=5,mango=7))
Enter fullscreen modeExit fullscreen mode

Output:

203012
Enter fullscreen modeExit fullscreen mode

Note that the name of the argument need not necessarily bekwargs, it can be anything, in this case, it'sfruits. But it's generally a standard way to use**kwargs as the name.

Conclusion

In this blog, we learned about two special keywords in Python -*args and**kwargs that make a Python function flexible to accept a variable number of arguments and keyword arguments respectively.

Thanks for reading!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Student || Python Lover || Flutter Enthusiast || Backend Developer
  • Location
    Bangalore
  • Education
    Bachelor of Technology
  • Work
    Application Developer @ Thoughtworks
  • Joined

More fromAshutosh Krishna

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp