Wednesday, January 15, 2025
HomeProgrammingUses of args and **kwargs in Python

Uses of args and **kwargs in Python

In Python, args and **kwargs are used to pass a variable number of arguments to a function.

1. args:
– Used to pass a variable number of non-keyword arguments (positional arguments) to a function.
– It collects extra positional arguments into a tuple.

See also  Difference between DELETE and TRUNCATE

Example:
python
def example(*args):
for arg in args:
print(arg)

example(1, 2, 3) # Output: 1 2 3

*2. **kwargs**:
– Used to pass a variable number of keyword arguments (named arguments) to a function.
– It collects extra keyword arguments into a dictionary.

Example:
python
def example(**kwargs):
for key, value in kwargs.items():
print(f”{key}: {value}”)

See also  Software Design Patterns Tutorial

example(a=1, b=2) # Output: a: 1 b: 2

Key Differences:
– args handles positional arguments, while **kwargs handles keyword arguments.
– args is a tuple, and **kwargs is a dictionary.

Both allow flexibility in function calls, accommodating varying numbers of arguments

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x