Back to Blog Home

How to Calculate Python List Length

Rob Timothy| Python | 6 months, 2 weeks



 

Python list length can be calculated using built in python function called len() which takes in the list as argument and returns the length or number of items in the list. 

 

Lets consider this python list for example :

 

avengers = [‘black panther’, ‘thor’, ‘iron man’, ‘black widow’, ‘captain America’, ‘hulk’]

 

Now to calculate the length of ‘avengers’ python list, you can simply use the len() built in function like :

 

len(avengers)

>> 6

 

Other than finding length of list sequence type, len() function can also be used to find the length of most of python sequences like a list, tuple, range , string or bytes as well as collections such as dictionary, set or frozen set. 

 

For example lets take this tuple

 

dc = (‘superman’, ‘batman’, ‘wonder woman’, ‘flash’)

 

And if we use the len() function to calculate the number of items in this tuple:

 

len(dc)

>>6 

 

 

So behind the scene the len() function actually uses a method called __len__  on the object whose length is to be calculated. So you can use it directly as well if you wan to find out the length of a list . For example 

 

avenrgers.__len__()

>>6 

 

 



Join 1000+ People Who Subscribe to Weekly Blog Updates

Back to Blog Home