Optimal solution
The most efficient and recommended way to find the list’s length is to use the built-in len() function in Python. It returns the total number of elements in the list, and it has a time and space complexity of O(1), which makes it super fast.
main_list = [1, 2, 3, 4, 5] print(len(main_list)) # Output: 5
The list data structure tracks its length internally, so the len() function does not have to count elements manually. It just retrieves a precomputed value stored in the list’s metadata. That’s why it has constant time of O(1).
Under the hood, what happens is that in CPython, the list object’s C structure (PyListObject) stores the list’s length as ob_size, which len() directly accesses.
Large list
Let’s say we have a list of 10 million elements. Let’s find out its length using len():
large_list = list(range(10000000)) print(large_list) # Output: [0, 1, 2, ..., 9,999,999] print(len(large_list)) # Output: 10000000
It outputs 10000000 (10 million or 1 Crore) instantly because it fetches the value from metadata. The Memory usage would be around ~80MB (for 10M integers in 64-bit Python).
From the output, we can say that the len() function works identically for all sizes.
Empty list
It is logical to assume that if a list is empty, it should have a length of 0 because it contains no elements.
empty_list = [] print(empty_list) # Output: [] print(len(empty_list)) # Output: 0
So, an empty list has zero length. However, if you want to check if a list is empty or not, you should use the “not” operator, like if not empty_list, because it is the most Pythonic way to check emptiness (even faster than the len() function).
Using manual counting with a loop
First, initialize a count variable to 0. Increment this count by 1 for each element encountered during the for loop iteration over the list.
After completing the loop, the count variable will contain the total number of elements in the list, suggesting its length.
list = [1, 2, 3, 4, 5] count = 0 for item in list: count = count + 1 print("The length of the list: ", count) # Output: The length of the list: 5
The main advantage of this approach is that you can use any iterables here, not just a list, and it can count it. However, its time complexity is O(n), which is inefficient for large lists.
Using sum() with a Generator
In this approach, we use a list comprehension to create a new list of only “1” elements.
The resulting new list will have the same number of elements as the original list.
Finally, the sum() function then adds up all the 1s in this newly created list. Since there are as many 1s as there were elements in the original list, the sum will equal the length of the original list.
list = [1, 2, 3, 4, 5] length_of_list = sum([1 for _ in list]) print("Length of the list:", length_of_list) # Output: Length of the list: 5
That’s it!