Unpacking Argument Lists in Python: How to Pass Lists and Tuples using *

When passing arguments to a function, sometimes your data is already grouped in a list or a tuple. Normally, you would need to extract elements from the list one by one using indices to specify them as arguments. However, in Python, using an asterisk (*) allows you to “expand” (unpack) the contents of the list and pass them to the function.

This article explains how to pass lists or tuples as positional arguments all at once.


目次

What is Argument Unpacking?

When calling a function, if you add * before a list or tuple variable, its elements are decomposed and assigned to the function’s positional arguments in order.

Syntax:

function_name(*list_variable)

For example, if you pass a list with three elements with a *, the function receives them as three independent arguments.


Specific Code Examples

As an example, we will use a function that accepts “width,” “height,” and “depth” of a rectangular box and calculates its volume.

1. Calling by Specifying Indices (Traditional Method)

If the data is in a list, you would typically write it like this:

def calculate_box_volume(width, height, depth):
    """Calculates the volume of a rectangular box"""
    return width * height * depth

# Size data (width, height, depth)
box_dimensions = [15, 10, 25]

# Specify indices one by one to pass
volume = calculate_box_volume(box_dimensions[0], box_dimensions[1], box_dimensions[2])

print(f"Volume: {volume}")

This method becomes longer and less readable as the number of arguments increases.

2. Calling with Argument Unpacking (Recommended)

Use * to expand the list and pass it.

# Pass with * before the list
volume_unpacked = calculate_box_volume(*box_dimensions)

print(f"Volume (Unpacked): {volume_unpacked}")

Output:

Volume: 3750
Volume (Unpacked): 3750

calculate_box_volume(*[15, 10, 25]) is interpreted internally as calculate_box_volume(15, 10, 25) and executed. You can see that it can be written very concisely.


Important Note: Matching the Number of Elements

When using this method, the number of elements in the list must match the number of mandatory arguments required by the function. If the numbers do not match, a TypeError will occur.

# If elements are missing
small_list = [10, 20]
# calculate_box_volume(*small_list) 
# TypeError: missing 1 required positional argument: 'depth'

# If there are too many elements
large_list = [10, 20, 30, 40]
# calculate_box_volume(*large_list)
# TypeError: takes 3 positional arguments but 4 were given

However, if the function is defined to accept variable-length arguments (*args), you can pass a list with any number of elements.

def sum_all(*values):
    return sum(values)

numbers = [1, 2, 3, 4, 5]
print(sum_all(*numbers)) # 15

Summary

  • Adding * before a list or tuple when calling a function expands the elements and passes them as positional arguments.
  • func(*my_list) is equivalent to func(my_list[0], my_list[1], ...).
  • The number of arguments must match the number of elements in the list.
  • This technique is very useful when feeding one line of data read from a database or file directly into a processing function.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次