List Length In Python: Using len() Function

To find the length of a list use the built-in len() function which takes a single parameter that is iterable. For example this could be a string, list, tuple or dictionary and here is how it would look:

>>> my_list = ['a', 'b', 'c']
>>> len(my_list)
3
>>> my_dict = {'a': 100, 'b': 200, 'c': 300}
>>> len(my_dict)
3
>>> my_str = 'How long is a piece of string?'
>>> len(my_str)
30

This may be the easiest and quickest way of being able to find the length of a list and other data types, but what if you want to exclude certain items from your list?

How do you find the length of a list without including certain types of elements, such as NoneType, or empty strings?

Count List Length Excluding Certain Elements

Suppose you have a list that contains empty elements, as None, in your list, like so:

>>> my_list = ['a', None, 'c']

If you needed to know the length of this list excluding certain elements, such as the element listed as None , how could you do so? Using the built-in len() function would produce the following:

>>> my_list = ['a', None, 'c']
>>> len(my_list)
3

To count the length of a list where certain elements are excluded would require a filter. By filtering a list using certain conditions and having that produce a new list you could then use the len on the new list.

In this example by using a list comprehension, which is just a way of looping through a list using one line, and applying an if condition on each element you can produce the desired list needed:

>>> my_list = ['a', None, 'c']
>>> filtered_list = [x for x in my_list if x is not None]
>>> len(filtered_list)
2

Applying the same formula len() to the new list helps to achieve the solution when only counting the length of a list when excluding certain criteria.

You could also have wrapped the two lines into one if you wanted to get it all in one line:

>>> my_list = ['a', None, 'c']
>>> len([x for x in my_list if x is not None]
2

Summary

To determine the length of a list in Python use the built-in len() function which not only counts the length of a string but also a list as well.

If required you can count the length of a list if you need to exclude certain elements from your original list by using list comprehensions.

Photo of author
Ryan Sheehy
Ryan has been dabbling in code since the late '90s when he cut his teeth exploring VBA in Excel. Having his eyes opened with the potential of automating repetitive tasks, he expanded to Python and then moved over to scripting languages such as HTML, CSS, Javascript and PHP.