![]() |
VOOZH | about |
In Python, lists are one of the most commonly used data structures to store an ordered collection of items.
In this article, we'll learn how to find the number of elements in a given list with different methods.
Example
Input: [1, 2, 3.5, geeks, for, geeks, -11]
Output: 7
Let's explore various ways to doing it:
The simplest and most efficient way is to use Python’s built-in len() function.
4
Explanation: len(a) returns the total number of items in the list a.
The length_hint() function from the operator module gives an estimated length of a collection.
4
Explanation:
We can declare a counter variable to count the number of elements in the list while iterating the list using a for loop.
4
Explanation: We initialize count as 0 and increment it for every element in the list.
We can also use the popular NumPy library's size() function.
4
Explanation: np.size(a) returns the total number of elements in the array or list.