Python / len() / Return the Length of a String
Python’s len(text) returns the number of Unicode code points in a string, including spaces and newlines. This is not always its byte count or the number of characters a reader perceives on screen. For collections that support length, such as lists, tuples, and dictionaries, it returns the number of items.
Basic usage, spaces, and newlines
len() takes one object that supports length. An empty string has length zero, and its enclosing quotation marks are not counted. A Unicode code point identifies a text element and is the unit represented by Python’s str type.
Use Python 3. Save each complete example in UTF-8 as length_example.py and run python length_example.py, or python3 where appropriate. Replace the file contents to run each example independently.
for text in ("abc", "", "a b", "a\nb"):
print(repr(text), len(text))
Expected output:
'abc' 3
'' 0
'a b' 3
'a\nb' 3
"a b" contains a space and "a\nb" contains one newline, so both have length three. Although the source notation \n uses two characters, its string value is one newline. Printing with repr() makes that distinction visible.
String length versus UTF-8 byte length
Encoding text as UTF-8 produces bytes for storage or transmission. len(text) counts code points, whereas len(text.encode("utf-8")) counts encoded bytes. In this example, \u00e9 denotes the accented character é.
text = "caf\u00e9"
data = text.encode("utf-8")
print(len(text))
print(len(data))
4
5
The text has four code points but five UTF-8 bytes because the last character requires two bytes. For a byte-based file or protocol limit, measure using the actual required encoding. String length is not a direct measurement of memory consumption either.
Combining characters and emoji can count differently
é can be represented as one code point or as e followed by a combining accent, totaling two. Similar appearance does not guarantee equal string values or lengths. Unicode grapheme clusters group code points into units approximating user-perceived characters.
import unicodedata
composed = "\u00e9"
decomposed = "e\u0301"
emoji = "\U0001f469\u200d\U0001f4bb"
print(len(composed), len(decomposed))
print(composed == decomposed)
print(len(unicodedata.normalize("NFC", decomposed)))
print(len(emoji))
1 2
False
1
3
Unicode normalization with unicodedata.normalize("NFC", text) composes canonically combinable representations. Here it changes a length-two representation to length one. It does not turn every emoji or combination into one code point: the woman-technologist emoji sequence in the example contains three.
Before implementing a “character limit,” decide whether it means code points, grapheme clusters, or bytes. NFC alone does not count graphemes; use an implementation of the relevant Unicode segmentation rules and check representative inputs.
Collection sizes and unsupported values
Lists, tuples, dictionaries, and sets also support length. Dictionaries count keys; sets count distinct elements. A nested list counts its outer items rather than automatically totaling everything inside.
print(len([10, 20, 30]))
print(len((10, 20)))
print(len({"a": 10, "b": 20}))
print(len({1, 1, 2}))
rows = [[1, 2], [3, 4]]
print(len(rows))
print(sum(len(row) for row in rows))
3
2
2
2
2
4
Numbers and None do not define length and raise TypeError. Convert a number to a string if you need the length of its representation, including a minus sign or decimal point. Being iterable does not imply support for len(): ordinary generators have no length.
for value in (1234, None):
try:
print(len(value))
except TypeError:
print("TypeError")
print(len(str(1234)))
items = (n * 2 for n in range(3))
try:
print(len(items))
except TypeError:
print("TypeError")
values = list(items)
print(len(values))
print(list(items))
TypeError
TypeError
4
TypeError
3
[]
Converting a generator to a list provides a count but consumes its elements and stores them in memory. The second list(items) is therefore empty. Avoid materializing huge data or infinite iterators merely to find a length.
A complete input length check
This function accepts strings and checks whether the value, after stripping surrounding whitespace, contains 1–12 code points. Empty and whitespace-only input is rejected; the original string is not modified.
def valid_name(text):
if not isinstance(text, str):
raise TypeError("name must be a string")
name = text.strip()
return 1 <= len(name) <= 12
for text in ("Ada", " ", "a" * 13, " Ada "):
print(repr(text), valid_name(text))
'Ada' True
' ' False
'aaaaaaaaaaaaa' False
' Ada ' True
The function does not validate content or character categories, remove all internal whitespace, or impose a visual character count. Align the service’s length unit, whitespace policy, allowed characters, and server-side checks so the interface and storage layer judge the same input consistently.




