How to find Python List Length

The list is one of Python’s built-in data structures that stores the elements in a sequence. A list is like a container and the order of the elements is changeable. A list can store any type of elements i.e. integers, floating-point numbers, complex numbers, etc. The elements of the same data type as well as mixed data type can be stored inside the list. The len() is a Python built-in function that is used to determine the length of any Python object. This post discusses how the list’s length can be found in Python.

A list in Python

In Python, a list is declared using a set of square brackets where a comma separates each element.  The list in Python is declared as follows:

#declaring Python list of integers
mylist1= [1,2,3,4,5,6,7,8]
#declaring Python list of strings
mylist2=["It","is","Python","list"]
#declaring a Python list of mixed data types
mylist3=[1,"a",10.02]

Every element inside the list is placed on a specific index.

Also learn: How to Reverse an Integer in Python

Find the list’s length in Python

Following are the most commonly used methods to find the length of a list in Python:

1. The len() method

2. The naive method

The len() method

It is a built-in function and returns the total number of elements in a list, tuple, dictionary and etc. it takes the list object as an argument and returns the length. The len() method is widely used by Python programmers. The syntax of the len() method is as follows:

len(list_obj)

Let’s see an example of Python len() method.

#declaring Python list of integers
mylist1= [1,2,3,4,5,6,7,8]
print("The length of first list is:",len(mylist1))
#declaring Python list of strings
mylist2=["It","is","Python","list"]
print("The length of second list is:",len(mylist2))
#declaring Python list of mixed data types
mylist3=[1,"a",10.02]
print("The length of third list is:",len(mylist3))

Output

The length of the first list is: 8

The length of second list is: 4

The length of third list is: 3

The naive method

Instead of the len() method, there is another interesting method to get the length of the list known as the naive method. Although it is not an efficient way to determine the length of the list using the naive method, however, it can be used when we don’t have any other efficient method to calculate the list’s length. In the naive method, a loop runs and the counter value is increased unless the last element of the list is counted. The naive method can be implemented as follows:

#declaring Python list of strings
mylist=["It","is","Python","list"]
#declaring a counter variable
countValue = 0
#implementing a list to iterate through the list
for i in mylist:
    countValue= countValue+ 1
#printing the length of list
print ("Length of list is : " + str(countValue))

Output

Length of the list is: 4

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Subscribe to get IQ's , Tutorials & Courses