Home >Backend Development >Python Tutorial >How Can I Unpack a Tuple to Pass Its Elements as Arguments to a Function in Python?

How Can I Unpack a Tuple to Pass Its Elements as Arguments to a Function in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-22 19:50:13760browse

How Can I Unpack a Tuple to Pass Its Elements as Arguments to a Function in Python?

Expanding Tuples into Arguments

Consider a function defined as follows:

def myfun(a, b, c):
    return (a * 2, b + c, c + b)

Given a tuple some_tuple = (1, "foo", "bar"), how can we utilize it to invoke myfun and obtain the output (2, "foobar", "barfoo")?

Answer:

To achieve the desired result, employ the * operator, to unpack the tuple and forward its elements as positional arguments to the function. The syntax for this is as follows:

myfun(*some_tuple)

By unpacking the tuple, the * operator effectively transforms some_tuple from a collection ((1, "foo", "bar")) into three individual arguments (1, "foo", and "bar"). These arguments are then passed to myfun in the order in which they appear in the tuple.

For a more comprehensive understanding of argument unpacking, refer to the dedicated documentation on the subject.

The above is the detailed content of How Can I Unpack a Tuple to Pass Its Elements as Arguments to a Function in Python?. 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