Can you LEN a list in Python?
Show
So, in this tutorial, we are going to discuss what we mean by the length of a list in Python, as well as how we can calculate it using various methods. We know, Python List is a mutable as well as ordered sequence. It may contain heterogeneous items as well as homogenous ones. It is a vastly used data structure in Python. For traversal as well as for performing some other operations on a list, we sometimes need to find the length of the list. How to Calculate the length of a List?Calculating the length or size of a list is analogous to finding the total number of items present in the same. For example, if we have a list, list1: The length of the list lis1 is 6. As the total number of elements or items is ‘6’. Methods of Finding the Length of a List in PythonThe length of a list can be calculated in Python by applying various techniques. Below we are going to discuss them one-by-one in detail. 1. Using the len() method in PythonThe built-in len() method in Python is widely used to calculate the length of any sequential data type. It calculates the number of elements or items in an object and returns the same as the length of the object. So, we can directly get the length of a list, through passing the same into the built-in len() method. Let us see how. #given list l=[11,22,33,44,55,66] #printing the length using len() print("The length of the list",l, "is :",len(l)) Output: The length of the list [11, 22, 33, 44, 55, 66] is : 6 In this code:
2. Custom Function to Calculate the Length of a ListNow let us define our own function in Python which will calculate the length of a list passed to it and return it where the function was called. Below is the calc_len() function that we define to find the length of a list. def calc_len(l): c=0 for i in l: c=c+1 return c #given list list1=['A',1,'B',2,'C',3,'D',4] #printing the length using calc_len() print("The length of the list",list1, "is :",calc_len(list1)) Output: Here,
ConclusionSo, in this tutorial, we learned how we can calculate or find the length of a list in Python. For any questions feel free to use the comment box below. References
Output: 3 Find the length of List with Python for loopIn order to find the length of the list in Python, using for loop is considered as a traditional technique or a naive method in the following manner:
counter = 0 for item in list: counter+=1 print(counter) Example: inp_lst = [‘Python’,’Java’,’Kotlin’,’Machine Learning’,’Keras’] size = 0 print(“Length of the input string:”) for x in inp_lst: —-size+=1 —-print(size) Output: Length of the input string: Find the length of a nested list in PythonLet us see how to find the length of a nested list. For this, we declared a list inside a list with the combination of a few other items. If we want the complete list length, then it considers the Nested list as one element. However, we can get the Nested list length using the index value. For example, the below code is finding the length of a nested list [20, 40, 50, 65, 22]. # Length of a String List nestedList = [‘Krishna’, 20, ‘John’, [20, 40, 50, 65, 22], ‘Yung’, 11.98] print(“\n Original List = “, nestedList) print(“Length of a Nested List = “, len(nestedList[3])) output: Original List = [‘Krishna’, 20, ‘John’, [20, 40, 50, 65, 22], ‘Yung’, 11.98] Find the length of a list of lists# Get the length of a list of lists a_list_of_lists = [[1,2,3], [4,5,6], [7,8,9]] print(len(a_list_of_lists)) # Returns: 3 Find the length of all items in a list of listsa_list_of_lists = [[1,2,3], [4,5,6], [7,8,9]] length = sum([len(sub_list) for sub_list in a_list_of_lists]) print(length) # Returns: 9 Find the length of string and dict with len function in PythonIn Python, we can also use the len function to get the length of a string. For example: We can also use len to get length of dict. len({‘Name’:’Steve’, ‘Age’:30, ‘Designation’:’Programmer’}) – This will return 3. Interview Questions of List length in Python 3Here are some interviews questions on get length of list Python. Q: What is “len function” time complexity? Q: How do I get the number of elements in a list? # empty list items = [] items.append(“apple”) items.append(“orange”) items.append(“banana”) # Get and print number of elements in the list Output: 3 Q: What is the best way to find the length of a list in Python 3? Q: How to get the Python length of the Array? Where Array is using in Java, C++ and other programming language and Lists are used in Python.
List being an integral part of Python day-day programming has to be learned by all the python users and having a knowledge of its utility and operations is essential and always a plus. So this article discusses one such utility of finding the no. of elements in a list. Method 1: Naive Method In this method, one just runs a loop and increases the counter till the last element of the list to know its count. This is the most basic strategy that can be possibly employed in the absence of other present techniques.
Output : The list is : [1, 4, 5, 7, 8] Length of list using naive method is : 5Method 2 : Using len() The len() method offers the most used and easy way to find the length of any list. This is the most conventional technique adopted by all programmers today.
Output: The length of list is: 4
Output: The length of list is: 3 Method 3 : Using length_hint() This technique is a lesser-known technique of finding list length. This particular method is defined in the operator class and it can also tell the no. of elements present in the list.
Output : Performance Analysis – Naive vs len() vs length_hint() When while choosing amongst alternatives it’s always necessary to have a valid reason why to choose one over another. This section does a time analysis of how much time it takes to execute all of them to offer a better choice to use.
Output : The list is : [1, 4, 5, 7, 8] Time taken using naive method is : 2.6226043701171875e-06 Time taken using len() is : 1.1920928955078125e-06 Time taken using length_hint() is : 1.430511474609375e-06Conclusion:In the below images, it can be clearly seen that time taken is naive >> length_hint() > len(), but the time taken depends highly on the OS and several of its parameter. In two consecutive runs, you may get contrasting results , in fact sometimes naive takes least time out of three.All the possible 6 permutations are possible.
length_hint() > naive > len(),
naive > len()=length_hint()
naive > length_hint() >len()
len > naive > length_hint() > naive Article Tags : Practice Tags : |