Python List len() Method



The Python List len() method is used to compute the size of a Python List. The size of a list is nothing but the number of elements present in it. However, if a list contains another list as its element, this method will consider the sub-list as a single entity rather than counting its individual elements as well.

The working of this method is actually simple. The method acts like a counter that is incremented every time a new element is defined and stored in the list. Therefore, when this method is called, it will not command the interpreter to traverse the list; instead the interpreter is asked to print the counter value that exists already. Hence, the time complexity of the len() method is O(1).

Syntax

Following is the syntax for the Python List len() method −

len(list)

Parameters

  • list − This is a list for which number of elements to be counted.

Return Value

This method returns the number of elements in the list.

Example

The following example shows the usage of len() method.

list1 = [123, 'xyz', 'zara']
list2 = [456, 'abc']
print("First list length : ", len(list1))
print("Second list length : ", len(list2))

When we run above program, it produces following result −

First list length :  3
Second list length :  2

Example

This method can also be used to check whether the list is empty or not. If the result of the Python List len() method is 0, the list is said to be empty. An example is given below.

list1 = []
print(len(list1))

list2 = [1, 2, 3, 4]
print(len(list2))

If we execute the given program, the output is displayed as follows −

0
4

The len() method can also be used in various scenarios. Let us see some examples demonstrating them.

Example

In this example, the method can be used with the conditional statements to check whether the list is empty or not.

list1 = [1, 2, 3, 4]
if len(list1) == 0:
   print("The list is empty!")
else:
   print("The list is not empty!")

If we compile and run the program above, the output is produced as follows −

The list is not empty!

Example

In another scenario, the len() method can also be used as a limit to the range in a loop statement. Let us look at the sample program below.

list1 = [1, 2, 3, 4]
print("The List is:")
for n in range(0, len(list1)):
   print(list1[n])

On executing the program above, the output is produced as follows:

The List is:
1
2
3
4
python_lists.htm
Advertisements