DEV Community

Cover image for *args and *kwargs, ARG! 🏴‍☠️
Richard
Richard

Posted on

*args and *kwargs, ARG! 🏴‍☠️

Most people learn about *args and **kwargs while learning Python without really understanding what's going on.

Functions have arguments. Here's a basic function that prints passed arguments.

def printArgs(first, second):
  print(first)
  print(second)

//invoke it
printArgs(1, 2)

//this will print:
1
2
Enter fullscreen mode Exit fullscreen mode

Well, that's cool I guess. But what if you have a case where you are not sure how many arguments will be passed? This function prints two. What if there's one?
TypeError: printArgs() takes exactly 2 arguments...
What if there are three? Or fifty? It'll only print two.

Here's where *args come in.

def printingArgs(*args):
  for arg in args:
    print(arg)

//invoke it
printingArgs(1, 2, 3, 4)

//prints
1
2
3
4
Enter fullscreen mode Exit fullscreen mode

Note: You can name *args whatever you want. It's the * at the beginning that makes it count. You can name it *asdf and then use

for thing in asdf:
   print(thing)
Enter fullscreen mode Exit fullscreen mode

and it will still work.

*kwargs are similar, but they mean Keyword Args; that is, arguments named with keywords like firstName="Bob" or something.

def printingArgsAndKwargs(*args, **kwargs):
  for arg in args:
    print(arg)
  for key, value in kwargs.items():
    print(key,value)

//invoke it
printingArgsAndKwargs(1, 2, 3, a=1, b=2, c=3)

//prints args first
1
2
3
//prints kwargs
('a', 1)
('b', 2)
('c', 3)
Enter fullscreen mode Exit fullscreen mode

And there you are, as simple as possible.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay