VMware ESXi and vSphere Cluster Management

How to Get the Length of a Python List

Learn how to count Python list elements with len(), understand zero-based indexes, find the last item, and safely handle empty lists.

A Python list is an ordered, mutable collection that can contain zero or more values. Each value stored in a list is an element. A list's length is the number of elements it currently contains.

For example, a list with three names has a length of 3. The length tells you how many items exist; it is not itself the position of the final item.

Use len() to Get a List's Length

len() is Python's built-in function for returning the size of supported objects, including lists. Its basic syntax is:

len(a_list)

The function returns an integer. You can print that integer directly or store it in a variable.

names = ["Ava", "Ben", "Chloe"]

print(len(names))

name_count = len(names)
print(name_count)

Both printed values are 3, because the list contains three elements.

Counting Elements in a List

Every list element contributes one to the length, regardless of the element's value or type. A text value, number, Boolean value, or another object each counts as one element.

values = ["ready", 42, True, [1, 2]]

print(len(values))  # 4

The nested list [1, 2] is one element of values. Its two inner values do not increase the length of the outer list.

List Length and Zero-Based Indexing

An index is the numeric position used to access an element. Python uses zero-based indexing, which means the first element has index 0, not index 1.

names = ["Ava", "Ben", "Chloe"]

print(names[0])  # Ava
print(names[1])  # Ben
print(names[2])  # Chloe

For a non-empty list with length n, the valid positive indexes range from 0 through n - 1. Therefore, a list with length 3 has indexes 0, 1, and 2. The number 3 is the count of elements, but it is already one position past the final valid positive index.

List contents | len() result | Valid positive indices | Last item index | Last item via negative index

["red", "blue", "green"] | 3 | 0 through 2 | 2 | -1

["only"] | 1 | 0 | 0 | -1

[] | 0 | none | none | none

Find the Last Item with len() - 1

To calculate the final valid positive index, subtract one from the list length:

names = ["Ava", "Ben", "Chloe"]

last_index = len(names) - 1
last_name = names[last_index]

print(last_index)  # 2
print(last_name)   # Chloe

Subtracting one is necessary because indexes begin at zero. With three elements, the indexes are 0, 1, and 2; the length is 3, so the final index is 3 - 1.

Use Negative Indexing for the Last Item

Negative indexing accesses positions from the end of a sequence. The index -1 always identifies the final element of a non-empty list.

names = ["Ava", "Ben", "Chloe"]

print(names[-1])  # Chloe

names[-1] is usually the clearest and most idiomatic way to retrieve the last item when you do not otherwise need the numeric index or the list length.

Use len(names) - 1 when the calculated index is useful for another operation, such as displaying the position or passing it to code that expects a positive index. Otherwise, prefer names[-1].

Handle an Empty List Safely

An empty list has no elements, so its length is zero:

items = []
print(len(items))  # 0

Because an empty list has no final element, both of these expressions raise IndexError, which is the exception Python raises when code requests a list position that does not exist:

items = []

items[len(items) - 1]  # IndexError
items[-1]              # IndexError

Check that the list is non-empty before accessing its last item. A list is truthy when it contains elements and falsy when it is empty:

items = ["task 1", "task 2"]

if items:
    print(items[-1])
else:
    print("The list is empty.")

You can also make the length check explicit:

items = []

if len(items) > 0:
    print(items[len(items) - 1])
else:
    print("There is no final item.")

The shorter if items: form is commonly preferred when you only need to test whether at least one element exists.

Common Length and Indexing Mistakes

Using the Length Directly as an Index

This code fails for a list containing three elements:

items = ["a", "b", "c"]
print(items[len(items)])  # IndexError

len(items) is 3, but the valid positive indexes end at 2. Use len(items) - 1 for the final positive index, or use items[-1].

Expecting len() to Return the Final Index

len() reports a count, not a position. For a list of length n, the final positive index is n - 1, provided the list is not empty.

Accessing the Last Item Without Checking for Emptiness

Neither items[-1] nor items[len(items) - 1] can produce an item when items is empty. Test the list first whenever its contents are uncertain.

Quick Reference

  • Use len(a_list) to get the number of stored elements.
  • The result of len() is an integer.
  • The first element has index 0.
  • For a non-empty list of length n, the final positive index is n - 1.
  • Use a_list[-1] to retrieve the last item concisely.
  • Check that a list is non-empty before using either last-item expression.

For more practice with list positions, see working with Python list length and indexing.