Python len(): How to Get the Length of a List
len() is one of Python's most-used built-in functions. It tells you how many items are in a list — and that number unlocks a surprising amount of power: safe indexing, loop control, size validation, progress tracking, and more. Virtually every non-trivial program that works with lists calls len() at some point.
Basic Usage
scores = [95, 82, 74, 88, 91]
print(len(scores)) # 5
# After removing an item, the length updates:
scores.pop()
print(len(scores)) # 4
# Empty list:
empty = []
print(len(empty)) # 0
Using len() to Access the Last Element
Because lists are zero-indexed, the last item is always at index len(list) - 1. (Though in modern Python, list[-1] is the simpler way to do this.)
items = ["alpha", "beta", "gamma", "delta"]
# Both of these access the last element:
print(items[len(items) - 1]) # delta
print(items[-1]) # delta (cleaner)
# Second to last:
print(items[len(items) - 2]) # gamma
print(items[-2]) # gamma (cleaner)
len() Enables Safe Indexing
Before accessing an index, check that it actually exists — len() makes this easy:
data = [10, 20, 30]
# Guard against IndexError:
index = 5
if index < len(data):
print(data[index])
else:
print(f"Index {index} is out of range (list has {len(data)} items)")
# Index 5 is out of range (list has 3 items)
Real-World Example: Progress Tracking
tasks = ["Design", "Build", "Test", "Deploy", "Launch"]
completed = ["Design", "Build"]
total = len(tasks)
done = len(completed)
remaining = total - done
print(f"Progress: {done}/{total} tasks complete") # Progress: 2/5 tasks complete
print(f"Remaining: {remaining} tasks") # Remaining: 3 tasks
percent = (done / total) * 100
print(f"{percent:.0f}% done") # 40% done
len() Works on Strings Too
The same function works on strings, tuples, and dictionaries — not just lists:
word = "algorithm"
print(len(word)) # 9
coords = (10, 20, 30)
print(len(coords)) # 3
info = {"name": "Alex", "age": 28}
print(len(info)) # 2 (number of key-value pairs)
Common Mistakes to Avoid
- Off-by-one errors: The last valid index is
len(list) - 1, notlen(list). Usinglist[len(list)]always raisesIndexError. - Comparing to length when you should check membership: To check if an item exists, use
if x in my_list, notif len(my_list) > 0. - Calling len() on a non-sequence:
len(42)raises aTypeError. It only works on collections.
nums = [1, 2, 3]
# Common mistake — accessing len() as the last index:
# print(nums[len(nums)]) # IndexError!
# Correct:
print(nums[len(nums) - 1]) # 3
print(nums[-1]) # 3 (simpler)
Key Takeaways
len(my_list)returns the number of elements — an integer you can use like any other number.- Valid indices range from
0tolen(list) - 1; going outside this range crashes withIndexError. - Use
len()to guard against index errors, control loops, and track progress. len()also works on strings, tuples, and dictionaries.
What to Learn Next
Now that you can measure a list, the natural next step is iterating over it. Learn for loops to process every element automatically, and range(len(list)) for index-based iteration. You'll use these patterns constantly in real Python programs.
