Lists are one of the most commonly used data types in Python and store collections of the same kind.
In this article, we will see how to find the length of a list.
len() Function
If you want to find the length of the given object, then in Python, there is a built-in function len(), giving you the length of the given object (object means a list, tuple, string, dictionary, etc.)
The syntax of the len() function is as follows:
len(list)
The function allows only one argument. The declared value is an integer that is the number of elements in the list.
Here is an example:
capitals = ['Tokyo', 'Sofia', 'India', 'Budapest', 'America'] list_len = len(capitals) print("The list has {0} elements.".format(list_len))
Output: The list has 5 elements.
- How to Convert String into Integer in Python
- How to split a string in Python
- How to Install Python Pip on Ubuntu 20.04
Using Loop
Another way to find the length of a list is to use them for a loop. This works by fixing up a counter and looping through all the elements of the list. On each repetition, the current value of the counter variable is incremented by one.
With the help of the following code, the snippet will get an idea of finding the length of an object using the loop.
capitals = ['Japan', 'America', 'India', 'Budapest', 'Italy'] counter = 0 for capital in capitals: counter = counter + 1 print("The list has {0} elements.".format(counter))
output: The list has 5 elements.
As we cannot trust this method, it favors using the len() function in Python.
Conclusion
In this article, we have seen finding the length of a list in Python list and using the len() function only. If you have any queries related to this len(), then feel free to connect us.