Python list length

How to use this len built in function to find the Python list length with few practical examples?. The 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 len function to count the number of elements or the size of a list. In this Python list length example, we declared an empty one. And, we used the len function to calculate for an empty one. Next, we are finding the size of an integer and it returns the total number of elements.

emptyLi = []

integerLi = [12, 22, 33, 44, 55, 66, 77]
[12, 22, 33, 44, 55, 66, 77]

Python get length of a List strings Example

When you use this len function on String items, it returns the total number of words in a string. Or, say, it finds the total items or words in the string. This Python example shows the total number of string items or the total number of words in the string List.

stringLi = ['Krishna', 'John', 'Yung', 'Ram', 'Steve']
print( len(stringLi))
['Krishna', 'John', 'Yung', 'Ram', 'Steve']

Mixed List 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 it.

Next, we are going to find the size (this includes tuple). Remember, len counts the complete Tuple as a single element.

mixedLi = ['Krishna', 20, 'John', 40.5, 'Yung', 11.98, 'Ram', 22]

mixedLi2 = ['Krishna', 20, 'John', (40, 50, 65), 'Yung', 11.98, 'Ram']

Nested List Example

Let us see how to find the length of a nested list input in Python programming. For this, we declared a nested one 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 size using the index value. For example, the below code is finding the length of a nested one [20, 40, 50, 65, 22].

nestedLi = ['Krishna', 20, 'John', [20, 40, 50, 65, 22], 'Yung', 11.98]
['Krishna', 20, 'John', [20, 40, 50, 65, 22], 'Yung', 11.98]

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. Once we got the items, we are finding the size using this len function.

intLi = []

Number = int(input("Please enter the Total Number of Items : "))

for i in range(1, Number + 1):
    value = int(input("Please enter the Value of %d Element : " %i))
print("\n Original = ", intLi)
print("Size of a Dynamic = ", len(intLi))
Python List Length 7