How to Get the Number of Elements in a Python List
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:
Using len() function
The simplest and most efficient way is to use Python’s built-in len() function.
a = [1, 2, 3, 4]
print(len(a))
Output
4
Explanation: len(a) returns the total number of items in the list a.
Using operator.length_hint()
The length_hint() function from the operator module gives an estimated length of a collection.
from operator import length_hint
a = [1, 2, 3, 4]
print(length_hint(a))
Output
4
Explanation:
- The code imports the length_hint function from the operator module.
- length_hint(a) returns the number of elements present in the list a which is 4. .
Using for loop
We can declare a counter variable to count the number of elements in the list while iterating the list using a for loop.
a = [1, 2, 3, 4]
count = 0
for _ in a:
count += 1
print(count)
Output
4
Explanation: We initialize count as 0 and increment it for every element in the list.
Using Numpy Library
We can also use the popular NumPy library's size() function.
import numpy as np
a = [1, 2, 3, 4]
print(np.size(a))
Output
4
Explanation: np.size(a) returns the total number of elements in the array or list.