Python len()関数:オブジェクトの長さを測る実践ガイド
Pythonでは、len()はオブジェクト内のアイテム数を返す組み込み関数です。文字列、リスト、タプル、辞書、その他のコレクションを扱う際、len()はコストのかかる反復処理なしでサイズを素早く効率的に取得する方法を提供します。
構文
len(value)
パラメータ
value – 長さを測定したいオブジェクト。
戻り値
指定されたオブジェクト内の要素数を表す整数を返します。
文字列
文字列の場合、len()はスペース、句読点、特殊文字を含むすべての文字をカウントします。Noneを渡すとTypeErrorが発生するので注意してください。
コレクション
- リスト & タプル – 要素数をカウント
- 辞書 – キー・値ペア数をカウント;キーと値は別々に数えない
- セット & フローズンセット – ユニークなアイテム数をカウント
エッジケース
- 空オブジェクト –
len([])は0を返す - 非対応型 – サイズを持たない型(例:
int)を渡すとTypeError
実例
1. 文字列の長さ
# 例1
str1 = "Welcome to Guru99 Python Tutorials"
print("The length of the string is:", len(str1))
出力: The length of the string is: 35
2. リストの長さ
# 例2
list1 = ["Tim", "Charlie", "Tiffany", "Robert"]
print("The length of the list is", len(list1))
出力: The length of the list is 4
3. タプルの長さ
# 例3
tup = ("Jan", "Feb", "March")
print("The length of the tuple is", len(tup))
出力: The length of the tuple is 3
4. 辞書の長さ
# 例4
dict_obj = {"Tim": 18, "Charlie": 12, "Tiffany": 22, "Robert": 25}
print("The length of the dictionary is", len(dict_obj))
出力: The length of the dictionary is 4
5. 配列の長さ (リスト相当)
# 例5
arr = ["Tim", "Charlie", "Tiffany", "Robert"]
print("The length of the array is", len(arr))
出力: The length of the array is 4
重要なポイント
len()は汎用的で効率的、あらゆるサイズ対応オブジェクトで使用可能- 整数を返し、0は空オブジェクトを示す
- オブジェクト型を常に検証し、
TypeErrorを回避
Python
- Python strip()メソッド完全ガイド:実践例付き
- Python str.count()マスター:文字と部分文字列のカウント実例集
- Python format()文字列を明確な例でマスター
- Python len()関数:オブジェクトの長さを測る実践ガイド
- Python String.find()メソッド完全ガイド:構文、例、代替手法
- Python yieldをマスター:ジェネレータvs return – 実践ガイド
- Python collections.Counter:効率的なカウント、更新、演算操作
- Java String.length()メソッド:文字列サイズ取得の実例解説
- Java String.charAt()完全解説:構文、戻り値、例外、実例
- Java String.contains()メソッド:部分文字列チェックの実践例
- Java String.endsWith()マスター:文字列サフィックスチェック実例付き