Site icon DesignLinux

How to Find the Length of a List in Python

How to Find the Length of a List in Python

In Python, lists are the mostly used data type to store collections of the same type data. This guide shows you how to find the length of a list in Python.

len() Function

The len() function is a built-in function of Python, used to get the length of a specified object. It can be a list , tuple, string, dictionary, etc.

Following is the basic syntax of the len() function:

len(list)

It accepts only one argument and returns integer number.

Let’s see an example,

os = ['Ubuntu', 'Debian', 'CentOS']

len_of_list = len(os)

print("The list has {0} elements.".format(len_of_list))
The list has 3 elements.

Using Loop

You also can get the length of a list using the for loop. You should set up a counter and execute the loop for all the elements of the object. It will do incremented in the current value of the counter variable.

Below is the code sample to find the number of elements of list using for loop:

os = ['Ubuntu', 'Debian', 'CentOS']
counter = 0

for s in os:
  counter = counter + 1

print("The list has {0} elements.".format(counter))
The list has 3 elements.

The first method is best to use.

Conclusion

You learned how to find the length of a list in Python using len() function.

To find the length of a list in Python list, use the len() function.

If you have any questions or feedback, feel free to leave a comment.

Exit mobile version