Understanding *args and **kwargs in Python
The wonderful use of *args and **kwargs in Python: the secret of flexible functions
In Python, *args
and **kwargs
are powerful tools for creating flexible functions that allow functions to accept a variable number of arguments. This is especially useful when you don't know in advance how many arguments will be passed to the function.
What is *args
?
*args
allows a function to accept any number of positional arguments. These parameters are stored in a tuple.
Example:
def print_numbers(*args): for number in args: print(number) print_numbers(1, 2, 3, 4, 5)
Output:
<code>1 2 3 4 5</code>
Here you can pass any number of numbers and they will all be printed. If no arguments are passed, args
will just be an empty tuple.
What is **kwargs
?
**kwargs
allows a function to accept any number of keyword arguments. These parameters are stored in a dictionary, where the keys are the parameter names and the values are their corresponding values.
Example:
def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="Alice", age=25, city="New York")
Output:
<code>name: Alice age: 25 city: New York</code>
Here you can pass any number of key-value pairs. If no keyword arguments are passed, kwargs
will just be an empty dictionary.
Use in combination *args
and **kwargs
You can use both *args
and **kwargs
in the same function. This allows you to handle both positional and keyword arguments.
Example:
def describe_person(*args, **kwargs): print("Attributes:") for arg in args: print(f"- {arg}") print("\nDetails:") for key, value in kwargs.items(): print(f"{key}: {value}") describe_person("Friendly", "Helpful", name="Bob", age=30, city="Boston")
Output:
<code>Attributes: - Friendly - Helpful Details: name: Bob age: 30 city: Boston</code>
Here, *args
collects positional parameters (such as "Friendly" and "Helpful"), and **kwargs
collects keyword parameters (such as name="Bob" and age=30).
Simple memory rules
- Use when you need to pass a variable number of positional arguments
*args
. - Use when you need to pass a variable number of keyword arguments
**kwargs
. - The order in a function signature should always be:
- General position parameters
*args
- Default keyword parameters
**kwargs
Practical examples for beginners
Example 1: A function for adding numbers
def add_numbers(*args): total = sum(args) print(f"The sum is: {total}") add_numbers(1, 2, 3, 4) add_numbers(10, 20)
Output:
<code>The sum is: 10 The sum is: 30</code>
Example 2: Greet people by name
def greet_people(**kwargs): for name, greeting in kwargs.items(): print(f"{greeting}, {name}!") greet_people(Alice="Hello", Bob="Hi", Charlie="Hey")
Output:
<code>Hello, Alice! Hi, Bob! Hey, Charlie!</code>
Example 3: Combining *args
and **kwargs
in a shopping list
def shopping_list(*items, **prices): print("Items to buy:") for item in items: print(f"- {item}") print("\nPrices:") for item, price in prices.items(): print(f"{item}: ${price}") shopping_list("Apples", "Bananas", Apples=2, Bananas=1.5, Oranges=3)
Output:
<code>Items to buy: - Apples - Bananas Prices: Apples: Bananas: .5 Oranges: </code>
Conclusion
By using *args
and **kwargs
you can make your Python functions more dynamic and flexible. This is especially useful when working with programs where the number of inputs may vary. Try these features out starting with small projects and you'll find them very handy!
The above is the detailed content of Understanding *args and **kwargs in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Fastapi ...

Using python in Linux terminal...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

About Pythonasyncio...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Discussion on the reasons why pipeline files cannot be written when using Scapy crawlers When learning and using Scapy crawlers for persistent data storage, you may encounter pipeline files...
