Python len() ビルトイン関数
オブジェクトの長さ(アイテム数)を返します。引数は、シーケンス(文字列、バイト、tuple、list、またはrangeなど)またはコレクション(dictionary、set、またはfrozen setなど)のいずれかです。
Introduction
Python の len() 関数は、オブジェクト内のアイテム数(長さ)を返すビルトイン関数です。オブジェクトは、シーケンス(文字列、リスト、タプルなど)またはコレクション(辞書やセットなど)のいずれかです。
Example
オブジェクトのアイテム数を返します:
len('hello')
len(['cat', 3, 'dog'])
5
3
Test of emptiness
空のテスト
文字列、リスト、辞書などの空のテストには len を使用せず、直接的なブール値評価を優先すべきです。
a = [1, 2, 3]
# bad
if len(a) > 0: # True と評価される
print("the list is not empty!")
# good
if a: # True と評価される
print("the list is not empty!")
the list is not empty!
the list is not empty!