Categories > Coding > Python >

Use of *args and **kwargs

UlaDeia

Senior Developer

Posts: 14

Threads: 9

Joined: Jul, 2022

Reputation: 4

Posted

As a result, I'm having trouble grasping the notion of *args and **kwargs.

So far, I have discovered:

*args = list of arguments - as positional arguments **kwargs = dictionary - whose keys become distinct keyword arguments and the values become values of these arguments

I'm not sure what programming task this would assist with.

Maybe:

Is it possible to pass lists and dictionaries as function parameters while also acting as a wildcard?

Is there a simple example of how *args and **kwargs are used?

In addition, the tutorial (source) I found just utilised the "*" and a variable name.

Are *args and **kwargs only placeholders, or do you actually utilise *args and **kwargs in the code?

  • 0

Alternate

stop take my rice

vip

Posts: 710

Threads: 113

Joined: Mar, 2022

Reputation: 40

Replied

I'll give you the answer you're looking for- *args and **kwargs are most commonly used to create optional arguments for, say, functions.

 

A required argument is created and used like this:

def MyFunc(argument):
    return argument

# Usage

result = MyFunc(“Hello, World!”)
print(MyFunc)
# Hello, World!

If the function is to be called without that argument provided, an error will occur as it is required.

 

*args and **kwargs are used to make optional arguments, like this: (using **kwargs)

def MyFunc(argument, **kwargs):
    argument2 = kwargs.get(“argument2”, “defaultvalue”)
    return argument + argument2

# Usage

result = MyFunc(“Hello, “, argument2=“World!”)
# Hello, World!

I don't know how to use *args but I do know how to use **kwargs, I hope this is somewhat helpful.

  • 1

test_bot2 is back

 

please stop taking my rice i need it to breathe

Murz

PixelPenguin

Posts: 240

Threads: 20

Joined: Jul, 2021

Reputation: 29

Replied

@87922 pretty sure he uses javascript, plus i mean sometimes even pro's mess up and need a little help or some insight :D

  • 0

Added

@87922 Sometimes it isn't that simple, some people have to take in information a certain way, maybe he couldn't find a good enough explanation for him online so he came to ask here :)

  • 0

 

Ty for rep: Swiney, Byoke, Lion, Locust, Waves, Weeb, Nickk, darkn, Atari, CubeFaces, Lux14, Rice, Delta, Syraxes, Aeon, Jordan, Pluto, and Hiroku!

P.S, I like cats better too!

Users viewing this thread:

( Members: 0, Guests: 1, Total: 1 )