keepcalculator

06 Numbers and Powers

Python len Function: Syntax, Use & Examples

Card No. 06·61777 · Updated · Standard formula, shown below

Total length 17 items
Text length
12 characters
You entered
List length
5 items
You entered
You enter
Text length, List length
You get
Total length
Rounding
0 dp

The Python len() function returns the number of items in an object, such as the characters in a string, elements in a list, or key-value pairs in a dictionary. You call it as len(object) and it always returns an integer. It is one of Python’s most frequently used built-in functions because it works across many data types.

Formula

The len() function has no mathematical formula; it simply counts the elements contained in the object you pass. Internally, Python calls the object’s __len__ method, which every built-in collection type implements. For a string, it counts Unicode code points; for a list or tuple, it counts elements; for a dictionary or set, it counts keys or members.

Worked Example

Using the default values from the calculator above:

  • Text length: 12 characters (e.g., “Hello World!”)
  • List length: 5 items (e.g., [1, 2, 3, 4, 5])

Calling len("Hello World!") returns 12. Calling len([1, 2, 3, 4, 5]) returns 5. The total length shown by the calculator is 12 + 5 = 17, which is the sum of both counts.

How len() Works Internally

When you call len(obj), Python looks for a special method named __len__ on the object’s class. If it exists, Python calls it and returns the result. For built-in types like lists, strings, and dictionaries, this method is implemented in C and runs in constant time, O(1). That means the operation takes the same amount of time regardless of how many items the object holds, because the length is stored as a separate attribute that is updated whenever the object changes.

If an object does not have a __len__ method, Python raises a TypeError with a message like “object of type ‘int’ has no len()”. This is why you cannot call len(42) or len(3.14).

What len() Works With

The len() function is supported by most built-in data types, including:

  • Strings: returns the number of characters, including spaces and punctuation.
  • Lists, tuples, ranges: returns the number of elements.
  • Dictionaries: returns the number of key-value pairs.
  • Sets and frozensets: returns the number of unique elements.
  • Bytes and bytearrays: returns the number of bytes.
  • Custom classes: if you define a __len__ method, you can make your objects work with len().

For example, len(range(10)) returns 10, and len({"a": 1, "b": 2}) returns 2.

Common Mistakes and Misconceptions

One frequent error is trying to use len() on an integer or a float. Another is forgetting that len() counts characters in a string, not words. For instance, len("Hello World") is 11, not 2. If you need the number of words, you must split the string first: len("Hello World".split()) returns 2.

Another misconception is that len() works on generators or iterators. It does not. A generator has no length because it is lazily evaluated and does not store all its values. Calling len(generator) raises a TypeError. You would need to convert it to a list first, but doing so consumes the generator.

Performance and Efficiency

Because len() is O(1) for built-in types, it is extremely fast and safe to use in loops or conditions. For example, checking if len(my_list) > 0 is common, though many Python developers prefer the more idiomatic if my_list: because empty collections are falsy. However, len() is still useful when you need the exact number for calculations or comparisons.

For strings, be aware that len() counts Unicode code points, not necessarily the number of visible characters. Some characters, like emoji composed of multiple code points, may count as more than one. For example, len("👨‍👩‍👧‍👦") returns 7 because the family emoji is made of several code points. If you need the number of grapheme clusters (user-perceived characters), you need a third-party library like grapheme.

Using len() with Custom Classes

You can make your own classes support len() by defining a __len__ method. This method must return an integer greater than or equal to zero. If it returns a negative number or a non-integer, Python raises a TypeError. Here is a simple example:

class Playlist:
    def __init__(self, songs):
        self.songs = songs
    def __len__(self):
        return len(self.songs)

my_playlist = Playlist(["Song A", "Song B"])
print(len(my_playlist))  # Output: 2

This is useful when you want your objects to behave like built-in collections.

Alternatives to len()

For most cases, len() is the right choice. However, there are situations where you might use alternatives:

  • Looping without index: use a for loop directly over the collection, no need for len().
  • Checking if empty: use if not my_list: instead of if len(my_list) == 0:.
  • Counting occurrences: use list.count(item) or collections.Counter.
  • Size in bytes: use sys.getsizeof() to get the memory footprint, not the number of elements.

Frequently Asked Questions

Why does len() not work on an integer?

Integers do not have a __len__ method because they are not collections. To get the number of digits in an integer, convert it to a string first: len(str(12345)) returns 5.

Can len() be used on a generator?

No, generators do not have a length because they are lazily evaluated and do not store all values. You can convert a generator to a list with list(generator), but that consumes the generator and may use a lot of memory.

Does len() count spaces in a string?

Yes, len() counts every character, including spaces, punctuation, and newline characters. For example, len("a b") returns 3.

What is the time complexity of len()?

For built-in types like list, string, and dict, len() operates in O(1) constant time because the length is stored as an attribute and updated as the object changes. It does not need to iterate through the elements.

Why does len() return a different value for emoji?

Some emoji, like family or flag emoji, are composed of multiple Unicode code points. len() counts code points, so it may return a number larger than the number of visible characters. For example, len("👨‍👩‍👧‍👦") returns 7.

Can I use len() on a NumPy array?

Yes, len() works on NumPy arrays, but it returns the size of the first dimension only. For a 2D array of shape (3, 4), len(arr) returns 3. Use arr.shape or arr.size for the full dimensions or total number of elements.

Related

Formula used
in t | Text length | characters | 12 | 0 | 100000
in d | List length | items | 5 | 0 | 100000
out total | Total length | items | t + d | 0

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →