What is Python List?

The list is an array collection in Python which is capable of storing multiple data types in it. It can store an integer, float, string, boolean, or even list inside a list. Python lists can be created using a square bracket or a list constructor function. The above square_bracket_list is a list created using square bracket([]), constructor_list is a list created using the list constructor. Both produce the same list output only. The list can be changeable, allow duplicates in it and be accessible by using an index.

Methods to find List Length

len() inbuilt functionlength_hint method from operatorcustom function & counter

Method 1: len() inbuilt function

The len() is a python inbuilt function used to find the length of the list and also for other iterables like Set, Tuples, Dictionary. Example Snippet Output I hope you have Python installed, if not, you can use an online Python compiler to practice the code.

Method 2: length_hint method from operator

length_hint is used to return a length of an iterable object (like List, Set, Tuples, Dictionary). It is available inside the python operator module. Not available like other in-built operators. Example Snippet Output

Method 3: Custom function & counter

In this method to find the length of the List, we are going to use the traditional method by using for-loop and counter. For that, we are going to write a function in python. which takes a list or other iterable as argument and return the length of an iterable. Custom function Snippet Example Snippet Output

Analysing those 3 methods

Performance Analysis for a large list Output As we can see length_hint is faster(3.0621886253356934e-06) when data are in millions. It’s because length hints are used by CPython runtime. Where it is called a python wrapper. Performance Analysis for a small list Output As we can see len() is faster(7.813796401023865e-07) when data are in thousands or lesser. In both cases, our custom function with counter takes more time than both methods.

Conclusion

In this article, we understand different ways to check the length of the list and how they fastly check the length of the list.