PYTHON MEBY

Pythonでリストの最大値・最小値を取得(max, min)

この記事では、Pythonのリストから最大値と最小値を取得する方法について説明します。組み込み関数`max()`と`min()`の使い方、そして数値以外のデータ型への適用方法を例を交えて解説します。

目次

max() 関数による最大値の取得

Pythonの`max()`関数は、リストやタプルなどのイテラブルオブジェクトから最大値を返す関数です。

numbers = [1, 5, 2, 8, 3]
max_number = max(numbers)
print(f'最大値: {max_number}') # 出力: 最大値: 8

上記の例では、`numbers`リストから最大値`8`を取得しています。

numbers = [1, 5, 2, 8, 3, 8]
max_number = max(numbers)
print(f'最大値: {max_number}') #出力: 最大値: 8

min() 関数による最小値の取得

Pythonの`min()`関数は、リストやタプルなどのイテラブルオブジェクトから最小値を返す関数です。`max()`関数と同様に使用します。

numbers = [1, 5, 2, 8, 3]
min_number = min(numbers)
print(f'最小値: {min_number}') # 出力: 最小値: 1

数値以外のデータ型のリストへの適用

`max()`と`min()`関数は、数値だけでなく、文字列などの他のデータ型にも適用できます。文字列の場合は、辞書順序で比較が行われます。

words = ['apple', 'banana', 'orange', 'grape']
max_word = max(words)
min_word = min(words)
print(f'最大の単語: {max_word}') # 出力: 最大の単語: orange
print(f'最小の単語: {min_word}') # 出力: 最小の単語: apple

文字列の比較は辞書式順序で行われます。

words = ['apple', 'Apple', 'banana', 'orange', 'grape']
max_word = max(words)
min_word = min(words)
print(f'最大の単語: {max_word}') # 出力: 最大の単語: banana
print(f'最小の単語: {min_word}') # 出力: 最小の単語: Apple

空リストへの対処

空リストに対して`max()`または`min()`関数を呼び出すと、`ValueError`が発生します。空リストかどうかを事前にチェックする必要があります。

numbers = []
try:
    max_number = max(numbers)
except ValueError:
    print('リストが空です') # 出力: リストが空です

関連記事