len() returns how many items an object contains. For a string, it counts every character between the quotation marks, including spaces and symbols; an empty string has length 0. section 7.3
Use len() with several common sequence objects:
- len("Boston 4 ever") evaluates to 13, while len("") evaluates to 0. section 7.3
- len((3, 5, "7", "9")) evaluates to 4 because the tuple contains four objects. section 10.2
- len(grocery) returns 3 for a grocery list containing milk, eggs, and bread; an empty list has length 0. section 25.2
Counting a grocery list
grocery = ["milk", "eggs", "bread"] print(len(grocery)) The program prints 3. The first element is at index 0, and the last element is at index len(grocery) - 1, or index 2. section 25.2
Quick checks:
- Predict the results of len(("hi", "hello", "hey", "hi")), len(("abc", (1, 2, 3))), len(((1, 2),)), and len(()). section 10.2
- Use len() before indexing a list so you can recognize when an index is beyond the list's limits and causes IndexError. section 25.2


