How to Get List Length in Python
A list in Python is a countable collection of elements. Counting the total elements in a list is a common programming task to determine how many indexes can be accessed among other things.
In this tutorial, we will learn how to get the total number of items in a Python list.
Python len() Function
To get the length of a list, use the Python
len() function and pass the list to evaluate as the first argument.
items = ['apple','orange','peach'] print(len(items))
Get the Length of Each Element in a List
len() function can be used on an iterable. Since strings are iterables we can get the length of each string in a list using a
for loop like this:
items = ['apple','orange','peach'] for i in items: print(len(i))
5 6 5
list contains mixed data types, such as numbers, convert them into strings using the Python
str() function before getting their length:
items = ['apple','orange','peach',4, 6, 12] for i in items: print(len(str(i)))
5 6 5 1 1 2
Getting the Length of Multidimensional Lists in Python
To get the total length of a multidimensional list, get the length of the list and multiply it by the total length of the nested lists:
items = [[1,2], [1,2,3], [1,2,3,4]] rows = len(items) columns = 0 for i in items: columns += len(i) print(rows * columns)