Table of Contents
The wonderful use of *args and **kwargs in Python: the secret of flexible functions
What is *args?
Example:
What is **kwargs?
Use in combination *args and **kwargs
Simple memory rules
Practical examples for beginners
Example 1: A function for adding numbers
Example 2: Greet people by name
Example 3: Combining *args and **kwargs
Conclusion
Home Backend Development Python Tutorial Understanding *args and **kwargs in Python

Understanding *args and **kwargs in Python

Jan 16, 2025 pm 10:16 PM

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)
Copy after login

Output:

<code>1
2
3
4
5</code>
Copy after login

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")
Copy after login

Output:

<code>name: Alice
age: 25
city: New York</code>
Copy after login

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")
Copy after login

Output:

<code>Attributes:
- Friendly
- Helpful

Details:
name: Bob
age: 30
city: Boston</code>
Copy after login

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

  1. Use when you need to pass a variable number of positional arguments*args.
  2. Use when you need to pass a variable number of keyword arguments**kwargs.
  3. 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)
Copy after login

Output:

<code>The sum is: 10
The sum is: 30</code>
Copy after login

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")
Copy after login

Output:

<code>Hello, Alice!
Hi, Bob!
Hey, Charlie!</code>
Copy after login

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)
Copy after login

Output:

<code>Items to buy:
- Apples
- Bananas

Prices:
Apples: 
Bananas: .5
Oranges: </code>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

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

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

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...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

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)...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

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

What is the reason why pipeline files cannot be written when using Scapy crawler? What is the reason why pipeline files cannot be written when using Scapy crawler? Apr 02, 2025 am 06:45 AM

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...

See all articles