Python len() 함수: 객체 길이 측정 실전 가이드
Python에서 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 방지.