1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

*argsと**kwargsの誤解

Last updated at Posted at 2025-04-17

*** は「アンパッキング(展開)するもの」と言われることが多いですが、
実際には状況によって「パック(まとめる)」動作にもなります。
この2つの記号は、関数の定義時と呼び出し時で全く逆の意味になるため、混乱しやすいポイントです。


✅ 結論

  1. 関数定義時*args, **kwargs は「複数の引数をまとめて受け取る」 → パック
  2. 関数呼び出し時*, ** は「シーケンスや辞書をばらして渡す」 → アンパック

🟣 関数定義時の例(パック)

def func(*args, **kwargs):
    print(args)
    print(kwargs)

func(1, 2, 3, a=10, b=20)
# → args: (1, 2, 3)
# → kwargs: {'a': 10, 'b': 20}
  • 位置引数は args という タプル
  • キーワード引数は kwargs という 辞書

🟢 関数呼び出し時の例(アンパック)

def greet(greeting, name):
    print(f"{greeting}, {name}!")

args = ("Hello", "Alice")
greet(*args)  # → Hello, Alice!
def display(voltage, action):
    print(f"{action} at {voltage}V")

d = {"voltage": 100, "action": "Run"}
display(**d)  # → Run at 100V

※ このように、すでにタプルやリスト、辞書として持っている引数を、*** を使って「ばらして渡す」ことで、個別の引数として関数に供給できます。


✅ まとめ

使用場面 * / ** の意味
関数 定義時 複数の引数をまとめる(パック)
関数 呼び出し時 タプル/リストや辞書をばらして渡す(アンパック)

📎 公式ソース:

1
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?