Works by

Ren's blog

@rennnosuke_rk 技術ブログです

【Python】実引数として渡すリストのアンパック

Python書いてて初めて知ったのでメモ。

関数に引数を渡すとき、以下のようにリストが格納された変数の頭に"*"をつけることで、 リストがアンパックされて引数の羅列として扱えるらしい。

import math

# 極座標系に変換
def polar_coordinates(x, y):
    r = math.sqrt(x ** 2 + y ** 2)
    theta = math.atan(y / x)
    return r, theta

x = 4.
y = 3.
coordinates = (x, y)
print polar_coordinates(*coordinates) # アンパック
# >> (5.0, 0.6435011087932844)

上記のコードは雑な例で申し訳ないのだけれども、 特定の括りでまとめた値をそのまま関数に渡したい時に便利かも。

追記

Pythonのバージョンが3.5以前だと、アンパックした引数のあとに名前なし引数をとれない。

import math

# 極座標系に変換
def polar_coordinates(x, y, z):
    r = math.sqrt(x ** 2 + y ** 2)
    s = math.sqrt(r ** 2 + z ** 2)
    theta = math.atan(y / x)
    phi = math.atan(z / r)
    return r, s, theta, phi

x = 4.
y = 3.
coordinates = (x, y)
print polar_coordinates(*coordinates,1)
# SyntaxError: only named arguments may follow *expression

リストやタプルなどをアンパックしつつ他の引数も取りたい場合、 引数の名前を明示的に指定するか、アンパック引数の前に他の引数を記述する。

# 引数の名前を明示
print polar_coordinates(*coordinates,z=1.)
# >> (5.0, 5.0990195135927845, 0.6435011087932844, 0.19739555984988078)

# アンパックする引数の前に、他の引数を記述
x = 4.
y = 3.
z = 1.
coordinates = (y, z)
print polar_coordinates(x, *coordinates)
# >> (5.0, 5.0990195135927845, 0.6435011087932844, 0.19739555984988078)