Content · Programming · Python

Python len() Function: Usage and Examples

len(value) reports the number of elements in a supported collection, such as a list, tuple, dictionary or string. String length counts Unicode code points rather than UTF-8 bytes or user-visible grapheme clusters. See.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

A form limits the number of selected products.

What You Need to Understand


len(value) reports the number of elements in a supported collection, such as a list, tuple, dictionary or string. String length counts Unicode code points rather than UTF-8 bytes or user-visible grapheme clusters.

When to Use It


A form limits the number of selected products.

Step-by-Step Python Example


items = ["apple", "pear", "apple"]
print(len(items))
print(len("café"))
print(len({"one": 1, "two": 2}))

How the Example Works


The list contains three elements including the duplicate; the string has four Unicode code points; the dictionary has two keys.

Example Output


3
4
2
Empty

A Second Example


Compare this smaller variation with the main example, then experiment with your own values.

names = []
print(names[-1] if len(names) > 0 else "Empty")

Important Behavior and Edge Cases


len() does not count the contents of a generator without consuming it by another method. It raises TypeError on types that have no defined length.

Try It Yourself


Check the number of items before reading the last one.

Common Beginner Mistakes


  • len() does not count the contents of a generator without consuming it by another method. It raises TypeError on types that have no defined length.
  • Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.

Key Takeaways


  • len(value) reports the number of elements in a supported collection, such as a list, tuple, dictionary or string.
  • The list contains three elements including the duplicate; the string has four Unicode code points; the dictionary has two keys.
  • len() does not count the contents of a generator without consuming it by another method.
Share this resourceSend this page to someone who may find it useful.