Home > Backend Development > Python Tutorial > Understanding *args and **kwargs in Python

Understanding *args and **kwargs in Python

Susan Sarandon
Release: 2025-01-16 22:16:13
Original
544 people have browsed it

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:

<code class="language-python">def print_numbers(*args):
    for number in args:
        print(number)

print_numbers(1, 2, 3, 4, 5)</code>
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:

<code class="language-python">def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="New York")</code>
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:

<code class="language-python">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")</code>
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

<code class="language-python">def add_numbers(*args):
    total = sum(args)
    print(f"The sum is: {total}")

add_numbers(1, 2, 3, 4)
add_numbers(10, 20)</code>
Copy after login

Output:

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

Example 2: Greet people by name

<code class="language-python">def greet_people(**kwargs):
    for name, greeting in kwargs.items():
        print(f"{greeting}, {name}!")

greet_people(Alice="Hello", Bob="Hi", Charlie="Hey")</code>
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
<code class="language-python">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)</code>
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!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template