How To Find Size of List in Python?

The list is a popular type in the Python programming language. List contains items that can be of different types like string, integer, floating-point, list, dictionary, etc. The size of the list is equal to the count of the list items. But this size is related to item counts not the memory usage size. The len() method is provided by both Python2 and Python3 with similar syntax and usage.

len() Method

Python provides the len() method, where the list can be provided as a parameter the size or item count of the list, will be returned as an integer. The len() method is a built-in method that is provided by default and there is no need to import any extra module.

mylist = [ 1 , 2 , 3 , 4 , 5 ]

print("Size of the list is",len(mylist))

# Output
# Size of the list is 5



mylist = [ "a" , "b" , "c" , 1 ,2 , 3 ]

print("Size of the list is",len(mylist))

# Output
# Size of the list is 6



mylist = [ "a" , "b" , "c" , [ 1 ,2 , 3 ] ]

print("Size of the list is",len(mylist))

# Output
# Size of the list is 4

Get Length Of A Line In A List

Well, you have learned how to find a list length. But how can you find the length of a list in a list? You can provide the list of lists to the len() method that will return the element count. In the following example, we will provide the mylist 3rd element to the len() method which is also a list. The output will be 3.

mylist = [ "a" , "b" , "c" , [ 1 ,2 , 3 ] ]

print("Size of the list is",len(mylist[3]))

# Output
# Size of the list is 3

Find List Slice Size

The list is a dynamic type where some part of the list can be returned and its size can be returned with the len() method. Returning some part of the list or some of the list items is called list slicing. Below we will return some of the list items by providing start or end indexes and count items with the len() method.

mylist = [ "a" , "b" , "c" , [ 1 ,2 , 3 ] ]

print("Size of the list is",len(mylist[1:]))

print("Size of the list is",len(mylist[:3]))

print("Size of the list is",len(mylist[2:]))

# Output
# Size of the list is 3
# Size of the list is 4
# Size of the list is 2

Use length_hint() Method

Python provides the operator module which has the length_hint() method in order to calculate the total number of elements of the provided iterable object. As a list is an iterable object the list can be provided to the length_hint() method in order to return the size of the list. But the performance of the length_hint() is lower than the len() method. If the performance is an important matter use the len() method.

import operator

mylist = [ "a" , "b" , "c" , [ 1 ,2 , 3 ] ]

print("Size of the list is",operator.length_hint(mylist))

Leave a Comment