Pythonのlen()関数は、シーケンス(リスト、タプル、文字列など)やコレクション(辞書、セットなど)の要素数を取得するための組み込み関数です。

len()関数の基本的な使い方は以下の通りです:

# リストの要素数を取得
numbers = [1, 2, 3, 4, 5]
length = len(numbers)  # 結果: 5

# 文字列の長さを取得
text = "Hello Python"
length = len(text)  # 結果: 11

# タプルの要素数を取得
fruits = ('apple', 'banana', 'orange')
length = len(fruits)  # 結果: 3

# 辞書の要素数を取得
person = {'name': 'John', 'age': 30, 'city': 'Tokyo'}
length = len(person)  # 結果: 3

よくあるエラーと解決方法

TypeError: object of type 'int' has no len()

数値型(int, float)に対してlen()関数を使用すると発生するエラーです。

# エラーの例
number = 12345
length = len(number)  # TypeError: object of type 'int' has no len()

# 解決方法:文字列に変換してから長さを取得
length = len(str(number))  # 結果: 5

TypeError: object of type 'NoneType' has no len()

None型の値にlen()関数を使用すると発生するエラーです。

# エラーの例
value = None
length = len(value)  # TypeError: object of type 'NoneType' has no len()

# 解決方法:値の存在確認を行う
value = None
if value is not None:
    length = len(value)

len()関数の活用例

リストが空かどうかの確認

data = []
if len(data) == 0:
    print("リストは空です")
# または
if not data:  # こちらの方が Pythonic
    print("リストは空です")

文字列の文字数制限チェック

password = "abc123"
if len(password) < 8:
    print("パスワードは8文字以上必要です")

まとめ

  • len()関数は、シーケンスやコレクションの要素数を取得できる
  • 数値型やNone型には直接使用できない
  • リストや文字列の長さチェックに便利
  • Pythonの基本的な組み込み関数として頻繁に使用される

以上のように、len()関数は非常に基本的でありながら、多くの場面で活用できる重要な関数です。