max() 最大値を取得
最終更新:2026-09-22
max() 最大値を取得
max() はイテラブル内の最大要素(または複数の引数の中で最大のもの)を返す;key 関数を指定できる。
| カテゴリ | 組み込み関数 |
|---|---|
| 種類 | 組み込み関数 |
| Python バージョン | all |
📝 構文
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])
⚙️ 引数
| iterable 必須 | An iterable, or the first compared value in the multi-arg form. |
|---|---|
| args 任意 | Additional values to compare (variadic). |
| key 任意 | A one-arg function used to derive the comparison key.(デフォルト値:None) |
| default 任意 | Value returned when the iterable is empty.(デフォルト値:None) |
戻り値:The largest item, or default when the iterable is empty.
💥 例外
ValueError— Raised when the iterable is empty and no default is given.TypeError— Raised when items cannot be compared.
▶ 例
下のコードを編集し「実行」をクリックすると、出力パネルに結果が表示されます:
実行結果:
5
c
apple
🏷️ 関連する組み込み関数
💡 関連するケース
さらに多くのケースは近日公開予定です。
❓ よくある質問
Qmax([]) はどうなりますか?
AValueError: max() arg is an empty sequence になります。default 引数を渡せば回避できます:max([], default=0) は 0 を返します。
Qmax(lst, key=len) の key は何をしますか?
A比較の基準を指定します:max(['apple', 'ant'], key=len) は 'apple'(最長)を返します。key は比較にだけ使い、返り値は元の要素のままです。
Qmax(1, 5, 3) と max([1, 5, 3]) の違いは何ですか?
A結果は同じです(どちらも 5)。前者は複数引数形式(引数を直接比較)、後者は単一引数形式(イテラブルの全要素を比較)です。
Qmax() に辞書を渡すと何を返しますか?
A最大のキーを返します。値でキーを取りたい場合は max(d, key=d.get) を使います。