🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

len()

AI & DATA SCIENCE // len

len() returns the number of items in a container — the character count of a string, the number of elements in a list/tuple/set, or the number of key-value pairs in a dict.

Syntax

len(s)

Deep Dive Course

len() works on any object that implements the __len__() dunder method — strings, lists, tuples, dicts, sets, and most other built-in containers. Internally, CPython just calls obj.__len__() and returns whatever integer it produces, which is also why you can add len() support to your own classes by defining that method.

1Understanding len()

len() works on any object that implements the __len__() dunder method — strings, lists, tuples, dicts, sets, and most other built-in containers. Internally, CPython just calls obj.__len__() and returns whatever integer it produces, which is also why you can add len() support to your own classes by defining that method.

💡

len() is O(1) for built-in containers — they cache their size — so it's always cheap to call, even inside a loop, unlike counting items manually with a generator.

editor.html
names = ["Ana", "Boris", "Cara"]
print(len(names))
localhost:3000

2Practical Example

Here is a real-world application of len() showing how it is used in production Python code.

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

p = Playlist(["Song A", "Song B"])
print(len(p))
localhost:3000

3Best Practices

Follow these guidelines when working with len():

1. Use if not container: rather than len(container) == 0 to check for emptiness — it's more idiomatic and works for any falsy check

2. Define __len__ on custom classes so they work naturally with len() and truthiness checks

3. Remember len() counts characters, not bytes, for a str — use len(s.encode()) if you need the byte count

⚠️

Tip: len() is O(1) for built-in containers — they cache their size — so it's always cheap to call, even inside a loop, unlike counting items manually with a generator.

editor.html
names = ["Ana", "Boris", "Cara"]
print(len(names))
localhost:3000

Examples

Example 01Basic Usage
names = ["Ana", "Boris", "Cara"]
print(len(names))
Example 02Advanced Example
class Playlist:
    def __init__(self, songs):
        self.songs = songs
    def __len__(self):
        return len(self.songs)

p = Playlist(["Song A", "Song B"])
print(len(p))

Best Practices

  • Use if not container: rather than len(container) == 0 to check for emptiness — it's more idiomatic and works for any falsy check
  • Define __len__ on custom classes so they work naturally with len() and truthiness checks
  • Remember len() counts characters, not bytes, for a str — use len(s.encode()) if you need the byte count

Interview Question

Why is len() a built-in function instead of a method on every object, like obj.length() in some other languages?

Hint: Consider consistency and how CPython implements it under the hood.

Python's design philosophy favors len(obj) over obj.len() partly for consistency — every container is measured the same way, from the outside — and because it lets CPython optimize the common case: for built-in types, len() reads a size field directly from the underlying C struct instead of dispatching a method call, making it faster than a typical method lookup. Custom classes can still opt in by implementing __len__().

Exercises

MediumPractice using len() in a real scenario.
View Solution
names = ["Ana", "Boris", "Cara"]
print(len(names))

Frequently Asked Questions

Why is len() a built-in function instead of a method on every object, like obj.length() in some other languages?

Python's design philosophy favors len(obj) over obj.len() partly for consistency — every container is measured the same way, from the outside — and because it lets CPython optimize the common case: for built-in types, len() reads a size field directly from the underlying C struct instead of dispatching a method call, making it faster than a typical method lookup. Custom classes can still opt in by implementing __len__().

Related Functions

__len__()listrange()