This post will discuss how to get the total number of items in a Python List.

1. Using len() function

The standard way to get the length of an object is with the built-in function len(). It returns an integer value greater than equal to 0, indicating the total number of items in the object. The object can be a sequence (such as a list, string, tuple, or range), or a collection (such as a dictionary or set). To use the len() function with a list, simply pass the list as an argument. Here is an example of how to use this function:

Download  Run Code

 
Note that it is not preferable to check whether a sequence or container is empty in boolean contexts using the len() function. The following solution shows the pythonic way to check whether a list is empty by placing the list in a boolean context. This works since a list in a boolean context is treated as False if empty, True otherwise.

Download  Run Code

2. Using __len__() function

The len() function is implemented with __len__, which returns the length of the object. Although not recommended, it can be called directly as:

Download  Run Code

 
According to the official sources, len(x) was chosen over x.len() since:

  1. Prefix notation just reads better than postfix.
  2. len(x) tells the result is an integer and the argument is some kind of container, whereas x.len() tells x has to be some kind of container implementing an interface or inheriting from a class that has a standard len().

3. Using numpy.size() function

Another way to get the number of items in a list in Python is to use the numpy.size() function from numpy module. Here is an example of how to use this method:

Download Code

4. Using for loop

Another way to get the number of items in a list is to use the for loop. The idea is to declare a counter variable to store the number of items in the list and increment it by one with each iteration of the loop. This works but it is more verbose than the len() function method. For example:

Download  Run Code

5. Using sum() function

Finally, we can use a generator expression that yields 1 for each item in the list to get the number of items in the list. Here is an example of how to use this method using the sum() function:

Download  Run Code

 
This method works, but it may not be very intuitive, as it uses a mathematical function for a non-mathematical purpose.

That’s all about getting the number of items in a list in Python.