How to use this len built in function to find the Python list length with few practical examples?. The Python len method is used to find and returns the length of any collections such as dictionary, tuple, etc.
The syntax of this len function to find the length of a list in python or to get the size is:
Python List length Example
We can use this function to count the number of elemnts or size of a list in python. In this Python list length example, we declared an empty one. And, we used the len function to calculate the length of an empty List. Next, we are finding the size of an integer list and it returns the total number of elements.
emptyList =  print(len(emptyList)) integerList = [12, 22, 33, 44, 55, 66, 77] print("integerList) print(len(integerList))
0 [12, 22, 33, 44, 55, 66, 77] 7
Python get length of a List strings Example
When you use this len function on String List, it returns the total number of words in a string. Or, say, it finds the length of the string items. This Python example shows the total number of string items or the total number of words in the string List.
stringList = ['Krishna', 'John', 'Yung', 'Ram', 'Steve'] print(stringList) print( len(stringList))
['Krishna', 'John', 'Yung', 'Ram', 'Steve'] 5
Python Mixed List Length Example
Apart from regular ones, you can also get the length of the mixed list. In the fifth line of code, we declared a Tuple inside a list. Next, we are going to find List size (this includes tuple). Remember, len counts the complete Tuple as a single element.
mixedList = ['Krishna', 20, 'John', 40.5, 'Yung', 11.98, 'Ram', 22] print(len(mixedList)) print() mixedList2 = ['Krishna', 20, 'John', (40, 50, 65), 'Yung', 11.98, 'Ram'] print(len(mixedList2))
Python Nested List Length Example
Let us see how to find the length of a input nested list. For this, we declared a nested list with the combination of a few other items. If you want the complete length, then it considers the Nested object as one element.
However, you can get the Nested list size using the index value. For example, the below code is finding the length of a nested list [20, 40, 50, 65, 22].
nestedList = ['Krishna', 20, 'John', [20, 40, 50, 65, 22], 'Yung', 11.98] print(nestedList) print(len(nestedList))
['Krishna', 20, 'John', [20, 40, 50, 65, 22], 'Yung', 11.98] 5
Dynamic Python List Length Example
This Program allows the user to enter the total number of elements. Next, using For Loop, it iterates each position and allows you to enter the individual elements. Within the loop, we used append function to add items to List. Once we got the items, we are finding the list length using this len function.
intList =  Number = int(input("Please enter the Total Number of Items in a List : ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) intList.append(value) print("\n Original List = ", intList) print("Length of a Dynamic List = ", len(intList))