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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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.