calendarcodediamondfacebookfingerglobalgoogleplushatenahomepagetopplainpocketrssservicetwitterwordpresshome2searchfoldernext-arrowback-arrowfirst-arrowlast-arrow

Python : len()は引数に渡したオブジェクトの長さや要素の数を取得する

len()は、引数に渡したオブジェクトの長さや要素の数を取得する組み込み関数である。

エンジニア速報は Twitter の@commteで配信しています。

Sponsored Link

len 関数のポイント

  • len 関数はシーケンスの長さ(要素の数)を返す
  • 0 以上の整数を返す
  • 0 以上の整数でない場合は全てエラーになる

引数はシーケンス (文字列、バイト列、タプル、リスト、range 等) 、もしくはコレクション (辞書、集合、凍結集合等) となる。

len 関数は内部で__len__()メソッドを実行しているので、len 関数と、__len__()メソッドの結果は同じになる

文字数の取得

文字列を渡すと、文字数を取得できる。

len('abcd') # 4 'abcd'.__len__() # 4

リストの要素数を取得

リストの要素数を数える。

x = [1, 2, 3, 4] len(x) # 4

タプルの要素数を取得

x = (1, 2, 3, 4) len(x) # 4

辞書の要素数を取得

x = {'a': 0, 'b': 1, 'c': 2, 'd':3} len(x) # 4

数値はエラーになる

しかし、数値はエラーになる

len(4) # Traceback (most recent call last) # <ipython-input-10-00d7b5c8c880> in <module>() # ----> 1 len(4) # # TypeError: object of type 'int' has no len()

len()は__len__()があれば動く。0 以上の整数を返す。

class A: def __len__(self): return 1 a = A() len(a) # 1

len()は、__len__()の値が int になっているか判定しているので、int 以外の値を返すとエラーになる。したがって 0 以上の整数でない場合は全てエラーになる。

class A: def __len__(self): return 5.0 a = A() len(a) # Traceback (most recent call last) # <ipython-input-6-c0b67c89f783> in <module>() # 4 # 5 a = A() # ----> 6 len(a) # # TypeError: 'float' object cannot be interpreted as an integer

Python おすすめ本

スポンサード リンク

Comments

Leave a Comment

コメントする

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください