len()
len() tells you how many items something holds: the characters in a string, the items in a list, the keys in a dict.
Used in 110 lessons of the course, from 00.01.
len(x) returns an integer: the number of items in x. It works on strings, lists, tuples, dicts, sets and other containers.
- On a string it counts characters.
- On a list or tuple it counts items.
- On a dict it counts keys.
It changes nothing; it only measures and hands you the number. That is why you see it inside other expressions, like an f-string.
The course uses it from lesson 00.01:
print(f"Glossary loaded: {len(GLOSSARY)} terms.")
Here len(GLOSSARY) counts how many entries the glossary has, and the f-string places that number in the message. The text stays true even when the glossary grows.
An empty container has length 0, which makes it handy for checking whether something has content.
Reach for it when: you need to know how many items a string, list, dict or other container holds, for example to show it in a message or compare it.
Examples
Common mistake
print(len(42))
Why: An integer is not a container, so it has no length.
How to write it: Use len(str(42)) if you want to count its digits.
Common mistake
words = ["a", "b", "c"] print(words[len(words)])
Why: Indexes start at 0, so the last one is len(words) - 1.
How to write it: Use words[len(words) - 1] or, better, words[-1].
