1. ホーム 
  2. 備忘録 
  3. Python

可変長引数

可変長引数とは

関数の引数について、あらかじめ個数が固定されておらず、任意の数を取ることができるもののことを可変長引数という

Python で可変長引数を取り扱う方法について以下に記載する


### 可変長引数(タプル型・リスト型)
# 渡された値を出力する
def say_something(word, *args):
    print(word, end='')
    for arg in args:
        print(arg, end='.')
    print('')


# そのまま引数を並べて渡す
say_something('Hi!', 'Mike', 'Nancy')  # Hi!Mike.Nancy.

# タプルにして渡す
t = ('Mike', 'Nancy')
say_something('Hi!', *t)  # Hi!Mike.Nancy.

# リストにして渡す
l = ['Mike', 'Nancy']
say_something('Hi!', *l)  # Hi!Mike.Nancy.


### 可変長引数(辞書型)
# メニューを出力する
def menu(**kwargs):
    print(kwargs)  # {'entree': 'beef', 'drink': 'ice coffee', 'dessert': 'ice'}
    for k, v in kwargs.items():
        print(k, v)
        # 結果:
        # entree beef
        # drink ice coffee
        # dessert ice


d = {
    'entree': 'beef',
    'drink': 'ice coffee',
    'dessert': 'ice'
}
menu(**d)


### おまけ
# 引数に可変長引数のタプル型や辞書型を混ぜた場合
def test_func(arg, *args, **kwargs):
    print(arg)  # banana
    print(args)  # ('apple', 'orange')
    print(kwargs)  # {'entree': 'beef', 'drink': 'coffee'}


test_func('banana', 'apple', 'orange', entree='beef', drink='coffee')