Home >Backend Development >Python Tutorial >How Can I Pass a Variable Number of Arguments to a Python Function?

How Can I Pass a Variable Number of Arguments to a Python Function?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 14:40:12251browse

How Can I Pass a Variable Number of Arguments to a Python Function?

Passing Variable Number of Arguments to Functions

In Python, it is possible to pass a variable number of arguments to a function, similar to the varargs concept in C/C .

Solution:

Python provides a special syntax *args that can be used as a non-keyword argument. When you use *args in a function definition, you can pass any number of arguments to that function.

def manyArgs(*arg):
  print("I was called with", len(arg), "arguments:", arg)

>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2, 3)
I was called with 3 arguments: (1, 2, 3)

As you can see, Python unpacks the arguments into a single tuple with all the arguments.

For Keyword Arguments:

If you need to handle keyword arguments separately, you can accept them as a separate actual argument. For example:

def manyArgsWithKeywords(*args, **kwargs):
  print("Non-keyword arguments:", args)
  print("Keyword arguments:", kwargs)

>>> manyArgsWithKeywords(1, 2, 3, keyword1="value1", keyword2="value2")
Non-keyword arguments: (1, 2, 3)
Keyword arguments: {'keyword1': 'value1', 'keyword2': 'value2'}

Note that keyword arguments must be specified explicitly after the varargs argument in the function definition.

The above is the detailed content of How Can I Pass a Variable Number of Arguments to a Python Function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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