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.
names = ["Ana", "Boris", "Cara"]
print(len(names))2Practical Example
Here is a real-world application of len() showing how it is used in production Python code.
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))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.
names = ["Ana", "Boris", "Cara"]
print(len(names))