len in Python: How the len() Function Measures Anything Sized

If you have written even a few lines of Python, you have probably reached for `len()`. It is one of the first built-in functions most people learn, and for good reason: almost every program eventually needs to ask “how many items are in this?” The `len()` function answers that question. It returns the number of items (the length) of an object — the count of characters in a string, elements in a list, keys in a dictionary, and so on.

But `len()` is also one of the most misunderstood functions for newcomers, especially developers arriving from JavaScript, Java, or C#. In those languages you write `array.length` or `str.length()`. In Python you write `len(x)` — a standalone function, not a method on the object. That small difference reveals a core piece of Python’s design philosophy, and understanding it will make you a noticeably more confident Python developer.

This tutorial covers everything `len()` does, every container type it works on, what it does *not* work on, how to use it well in loops and conditions, and what happens under the hood.

Key Takeaways
• `len()` is a built-in function that returns the number of items in a sized object: `len(x)`, never `x.len()`.
• It works on strings, lists, tuples, dictionaries, sets, ranges, and any object that defines `__len__`.
• On a dictionary, `len()` returns the number of keys; on a string, the number of characters.
• `len()` does not work on integers, floats, or `None` — those are not containers, so you get a `TypeError`.
• It runs in O(1) constant time: Python stores the length and does not recount on each call.
• For emptiness checks, `if not x:` is more Pythonic than `if len(x) == 0:`.

What does the len() function actually do in Python?

At its simplest, `len()` takes one argument — a container or “sized” object — and returns an integer: how many items it holds.

“`python fruits = [“apple”, “banana”, “cherry”] print(len(fruits)) “`

Output:

“` 3 “`

That is the whole core idea. You pass in something that holds items, and you get back the count of those items. The return value is always a non-negative integer, and it is always exact — Python does not estimate or approximate.

How does len() work on strings?

For a string, `len()` returns the number of characters, including spaces and punctuation.

“`python greeting = “Hello, world!” print(len(greeting))

empty = “” print(len(empty))

spaces = ” ” print(len(spaces)) “`

Output:

“` 13 0 3 “`

Notice that `”Hello, world!”` is 13 characters — the comma, the space, and the exclamation mark all count. An empty string has length 0, and a string of three spaces has length 3, because spaces are characters too. This is a frequent source of confusion: `len()` measures characters, not “words” or “visible content.”

How does len() work on lists and tuples?

Lists and tuples both report the number of top-level elements they contain.

“`python numbers = [10, 20, 30, 40] print(len(numbers))

coordinates = (4.5, 9.1) print(len(coordinates))

nested = [[1, 2], [3, 4], [5, 6]] print(len(nested)) “`

Output:

“` 4 2 3 “`

The last example is important: `nested` contains three items, and each item happens to be a list. `len()` counts the *outer* elements — it does not flatten or recurse. So `len(nested)` is 3, not 6.

What does len() return for a dictionary?

For a dictionary, `len()` returns the number of keys (which equals the number of key-value pairs).

“`python user = {“name”: “Ravi”, “role”: “developer”, “active”: True} print(len(user)) “`

Output:

“` 3 “`

The dictionary has three keys, so `len(user)` is 3. The values are not counted separately — one key-value pair counts as one item.

How does len() handle sets and ranges?

A set reports its number of unique elements, and a range reports how many numbers it would produce.

“`python unique_ids = {7, 7, 7, 8, 9} print(len(unique_ids))

r = range(0, 10, 2) print(len(r)) “`

Output:

“` 3 5 “`

The set `{7, 7, 7, 8, 9}` collapses to `{7, 8, 9}`, so its length is 3 — duplicates are removed automatically. The `range(0, 10, 2)` would generate `0, 2, 4, 6, 8`, which is 5 numbers. Notably, `len()` on a range is instant even for `range(1_000_000)`; Python computes the count arithmetically without generating a single number.

Here is a quick reference for what `len()` returns across the common built-in types:

Type What `len()` returns Example Result
`str` Number of characters `len(“data”)` `4`
`list` Number of elements `len([1, 2, 3])` `3`
`tuple` Number of elements `len((1, 2))` `2`
`dict` Number of keys `len({“a”: 1})` `1`
`set` Number of unique elements `len({1, 1, 2})` `2`
`range` Count of numbers in the range `len(range(5))` `5`
`bytes` Number of bytes `len(b”hi”)` `2`

Why is len() a function and not a method?

This is the question that trips up almost everyone coming from another language. In JavaScript you write `arr.length`. In Java you write `str.length()`. So why does Python make you write `len(x)` instead of `x.len()`?

If you try the method syntax, Python rejects it:

“`python my_list = [1, 2, 3] print(my_list.len()) “`

Output:

“` AttributeError: ‘list’ object has no attribute ‘len’ “`

The answer is a deliberate design choice, and it is worth understanding.

`len()` being a standalone function rather than a method feels odd at first, but it reveals a core Python design principle. `len()` works on *any* object that implements the `__len__` protocol, so the same `len()` call uniformly measures strings, lists, dicts, sets, custom objects, and anything else that knows its own size. Other languages scatter this concept across types that each name it differently — `.length` on a JavaScript array, `.length()` on a Java string, `.size()` on a C++ vector, `.count` elsewhere. Python centralizes it into one function that asks every object the same question: “how big are you?” through a shared protocol.

This is why `len()` feels universal and consistent, and why a class you write becomes `len()`-compatible the moment you define `__len__`. The lesson goes beyond `len` itself: Python favors a small set of universal functions — `len()`, `iter()`, `next()`, `str()` — that work across all types via protocols, rather than per-type methods scattered everywhere. Once you internalize that `len()` works on “anything sized,” you never have to wonder which method a new container type uses to report its length. It is always `len()`.

What does len() NOT work on?

Because `len()` needs something with a size, it fails on values that are not containers. Integers, floats, booleans, and `None` are single values, not collections — they have no “number of items.”

“`python print(len(42)) “`

Output:

“` TypeError: object of type ‘int’ has no len() “`

“`python print(len(None)) “`

Output:

“` TypeError: object of type ‘NoneType’ has no len() “`

“`python print(len(3.14)) “`

Output:

“` TypeError: object of type ‘float’ has no len() “`

The error message is precise and helpful: the object’s type “has no len().” If you ever see this `TypeError`, it means you handed `len()` something that is not a sized container. A common real-world cause is a variable that you expected to be a list but is actually `None` — for example, a function that returned nothing. When that happens, check where the value came from rather than blaming `len()`.

If you genuinely need to know “how many digits are in this number,” convert it to a string first:

“`python number = 12345 print(len(str(number))) “`

Output:

“` 5 “`

How do you use len() in loops and conditions?

A very common use of `len()` is checking whether a container is empty before doing work.

“`python cart = []

if len(cart) == 0: print(“Your cart is empty.”) else: print(f”You have {len(cart)} items.”) “`

Output:

“` Your cart is empty. “`

This works, but experienced Python developers usually write emptiness checks more concisely. In Python, empty containers are “falsy,” so you can test them directly:

“`python cart = []

if not cart: print(“Your cart is empty.”) “`

Output:

“` Your cart is empty. “`

Both versions behave identically here, but `if not cart:` is considered more Pythonic for a pure emptiness check. Reach for `len()` explicitly when the actual *count* matters — for example, `if len(cart) > 5:` or when you want the number for a message. Use `if not cart:` when you only care whether something is empty.

Should you use range(len(x)) for indexing?

You will often see beginners loop over a list by index using `range(len(x))`:

“`python colors = [“red”, “green”, “blue”]

for i in range(len(colors)): print(i, colors[i]) “`

Output:

“` 0 red 1 green 2 blue “`

This works, and `range(len(…))` is a legitimate pattern when you truly need the numeric index — for instance, to modify a list in place or to compare adjacent elements. But when you need both the index and the value, `enumerate()` is cleaner and more readable:

“`python colors = [“red”, “green”, “blue”]

for i, color in enumerate(colors): print(i, color) “`

Output:

“` 0 red 1 green 2 blue “`

`enumerate()` gives you the index and the item together without manual indexing, so you avoid the `colors[i]` lookup entirely. If you only need the values and not the index, skip both and iterate directly: `for color in colors:`.

What is the difference between len() and count()?

These two are easy to confuse, but they answer different questions. `len()` gives the total number of items. `count()` is a method that gives the number of times one specific value appears.

“`python votes = [“yes”, “no”, “yes”, “yes”, “no”]

print(len(votes)) print(votes.count(“yes”)) print(votes.count(“no”)) “`

Output:

“` 5 3 2 “`

So `len(votes)` is 5 (five votes total), while `votes.count(“yes”)` is 3 (the value “yes” appears three times). Note also that `count()` *is* a method (`votes.count(…)`), reinforcing the contrast: `len()` is the universal protocol-based function, whereas `count()` is specific behavior that lists and strings provide. For a deeper look at counting occurrences, see .

### Build and run your Python work on infrastructure you control — with DarazHost

Learning `len()` is the easy part. Running real data-processing pipelines — iterating over millions of records, measuring large collections, and timing performance — needs a dependable environment. DarazHost VPS and dedicated servers give developers a real, controllable Python environment: write and run data-processing code on guaranteed resources with full root access. It is the dependable home your Python work needs, backed by 24/7 support, so your scripts run on hardware you actually control rather than a shared sandbox that throttles you mid-job.

How does len() work under the hood?

When you call `len(x)`, Python looks for a special method named `__len__` on the object’s type and calls it. This is the protocol that makes `len()` universal. Any object that defines `__len__` becomes `len()`-compatible automatically:

“`python class Playlist: def __init__(self, songs): self.songs = songs

def __len__(self): return len(self.songs)

my_playlist = Playlist([“Song A”, “Song B”, “Song C”]) print(len(my_playlist)) “`

Output:

“` 3 “`

By defining `__len__`, our custom `Playlist` class works with the built-in `len()` exactly like a list or string does. We did not have to register anything or inherit from a special base class — defining the method was enough. This is the protocol-based design in action.

Why len() is fast: O(1) performance

A crucial practical detail: `len()` runs in O(1) constant time for all built-in containers. Python does not walk through the items and count them on each call. Instead, every list, dict, set, and string stores its own length internally and updates that stored value whenever items are added or removed. When you call `len()`, Python simply reads that stored number.

This means calling `len()` on a list of ten items and a list of ten million items takes the same negligible amount of time. You can safely call `len()` inside conditions and loops without worrying about performance, because there is no hidden recount happening. (The one caveat: if you write your own `__len__`, make sure *it* is fast, since Python will trust whatever your method does.)

Frequently asked questions about len in Python

Does len() count from 0 or 1? `len()` returns a true count starting from 1 — a list of three items returns `3`. This is different from *indexing*, which starts at 0. So the valid indices for a list of length 3 are 0, 1, and 2, and the last index is always `len(x) – 1`.

Why does len() give a TypeError on my variable? The most common cause is that your variable holds an `int`, `float`, or `None` instead of a container. This often happens when a function returns nothing (which gives `None`) and you call `len()` on the result. Print or inspect the variable’s type with `type(x)` to confirm what it actually is.

Is len() a method or a function? `len()` is a built-in function. You call it as `len(x)`, not `x.len()`. Writing `x.len()` raises an `AttributeError` because the object has no `len` method — Python deliberately centralizes length-checking in one function.

How do I get the length of a number in Python? Numbers have no length, so convert to a string first: `len(str(12345))` returns `5`. This counts the digits as characters. Remember that a negative sign or decimal point would also count as a character.

Is len() slow on large lists? No. `len()` is O(1) on all built-in containers because Python stores the length and reads it directly rather than recounting. It is one of the cheapest operations you can perform, regardless of how large the container is.

Wrapping up

The `len()` function is small but foundational. It returns the number of items in any sized object — characters in a string, elements in a list or tuple, keys in a dict, unique members of a set, or numbers in a range — and it refuses anything that is not a container. Remember the three habits that mark a confident Python developer: write `len(x)` not `x.len()`, prefer `if not x:` for plain emptiness checks, and reach for `enumerate()` over `range(len(x))` when you need both index and value. Above all, internalize the deeper lesson — Python gives you a handful of universal functions that work across all types through shared protocols, and `len()` is the clearest example of that philosophy.

For the bigger picture on running Python in an environment you fully control, see the pillar guide: Hosting for Developers: The Complete Guide to a Real Environment You Control.

About the Author

Leave a Reply