How do you get the length of a list in Python?
Short answer: use the built-in len() function. len(fruits) returns how many items the list has. An empty list returns 0.
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # 3
print(len([])) # 0Lists have no .length property and no .len() method like in other languages. In Python you always write len(my_list).
len() counts the items of a list, returns 0 when it is empty, only counts the top level of a nested list and fails with numbers.
Every way to count items in Python
| What you want | Code | Result |
|---|---|---|
| Items in a list | len(["apple", "banana", "cherry"]) | 3 |
| Check if a list is empty | if not fruits: | True when empty |
| Every item in a nested list | sum(len(x) for x in [[1, 2], [3, 4, 5]]) | 5 |
| Unique items | len(set([3, 8, 8, 5, 3])) | 3 |
| How many times a value appears | [3, 8, 8, 5, 3].count(8) | 2 |
| Items that meet a condition | sum(1 for n in nums if n > 4) | 3 |
| Characters in a string | len("hello") | 5 |
| Keys in a dict, items in a tuple or set | len({"a": 1, "b": 2}), len((1, 2, 3)) | 2, 3 |
| Rows of a pandas DataFrame | len(df) or df.shape[0] | Number of rows |
| Elements of a NumPy array | arr.size (all), len(arr) (first dimension) | 6, 2 |
Use len() with lists
len() works with any list, whatever the items are. It counts items, not values, so None, "" and 0 also count:
print(len([1, None, "", 0])) # 4The length changes when you add or remove items:
fruits = ["apple", "banana", "cherry"]
fruits.append("kiwi")
print(len(fruits)) # 4
fruits.pop()
print(len(fruits)) # 3len() is instant even with millions of items, because Python keeps the size stored in the list. You don't need to save it in a variable to make your code faster.
