How to Get the Length of a List in Python
Learn how to count Python list elements with len(), understand zero-based indexes, safely retrieve the last item, and avoid IndexError with empty lists.
A Python list is an ordered, mutable collection of items. Each individual item stored in a list is called an element. A list's length is the total number of elements it contains.
Every item counts as one element, regardless of its value or data type. For example, a string, an integer, and another list each count as one element when they are stored directly in a list.
Use len() to Get a List's Length
len() is a built-in Python function that returns the size of a sized object. The general syntax is:
len(sequence)
Pass the list as the argument. The result is an integer representing the number of elements in the list.
names = ["Ava", "Ben", "Chloe", "Diego"]
print(len(names))
Output:
4
This list has four elements, so len(names) returns the integer 4.
Store the Length in a Variable
You can assign the returned integer to a variable and use it later:
last_names = ["Garcia", "Patel", "Nguyen"]
count = len(last_names)
print("Number of names:", count)
Output:
Number of names: 3
Examples of List Lengths
An empty list contains no elements, so its length is zero:
empty_list = []
print(len(empty_list))
Output:
0
Repeated values still occupy separate list positions. Each occurrence counts:
scores = [10, 10, 7, 10]
print(len(scores))
Output:
4
The value 10 appears three times, but the list has four elements because each occurrence is an element.
List Length Versus Index Positions
An index is a numeric position used to access an item in an ordered collection. Python uses zero-based indexing: the first element has index 0, not index 1.
The length tells you how many elements exist. It is not itself the last valid index. If a list has length n, its valid indexes run from 0 through n - 1.
| List contents | Length returned by len() | Valid positive indexes | Last-element index |
|---|---|---|---|
[] | 0 | None | None |
["red"] | 1 | 0 | 0 |
["red", "green", "blue"] | 3 | 0, 1, 2 | 2 |
["a", "b", "c", "d"] | 4 | 0, 1, 2, 3 | 3 |
For example:
colors = ["red", "green", "blue"]
print(colors[0]) # first element
print(colors[2]) # last element
Because the list has length 3, index 3 is not valid. The final valid positive index is 3 - 1, or 2.
Find the Last Element with len(my_list) - 1
To calculate the final valid positive index, subtract one from the list length:
items = ["notebook", "pen", "ruler"]
last_index = len(items) - 1
last_item = items[last_index]
print(last_index)
print(last_item)
Output:
2
ruler
Subtracting one is necessary because counting starts at one, while indexes start at zero. A three-element list has a length of 3, but its positions are 0, 1, and 2.
Preferred Direct Access: Negative Indexing
Python provides negative indexing for accessing items from the end of a sequence. The index -1 identifies the final item:
items = ["notebook", "pen", "ruler"]
last_item = items[-1]
print(last_item)
Output:
ruler
items[-1] is usually the concise, standard way to retrieve the last item. The calculated-index approach remains useful for understanding the relationship between length and zero-based positions.
| Method | Expression | Works for empty lists? | Best use |
|---|---|---|---|
| Calculated positive index | items[len(items) - 1] | No | Learning or explicitly calculating the final valid index |
| Negative index | items[-1] | No | Concise direct access to the last item |
Both methods require a non-empty list. An empty list has no final element.
Safely Handle an Empty List
len([]) returns 0. Attempting to retrieve the last item from an empty list raises IndexError, an exception raised when code requests a list position that does not exist.
items = []
# Both expressions raise IndexError:
# items[-1]
# items[len(items) - 1]
Check whether the list contains an item before indexing it. A list is truthy when it has elements and falsy when it is empty:
items = ["notebook", "pen"]
if items:
print("Last item:", items[-1])
else:
print("The list is empty")
You can also make the condition explicit with len(items) > 0, although if items: is the usual Python style:
if len(items) > 0:
last_item = items[len(items) - 1]
print(last_item)
What Else Can len() Count?
len() works with strings, tuples, dictionaries, sets, and other sized collections. What it counts depends on the collection type:
word = "Python"
coordinates = (10, 20)
settings = {"theme": "dark", "font_size": 14}
unique_numbers = {2, 4, 6}
print(len(word)) # 6 characters
print(len(coordinates)) # 2 tuple elements
print(len(settings)) # 2 dictionary keys
print(len(unique_numbers)) # 3 set elements
For a dictionary, len() returns the number of keys. For a set, it returns the number of distinct elements.
Common Mistakes and Fixes
Using the Length as the Last Index
Problem: Code uses items[len(items)] to access the final item.
Cause: The length is one greater than the final zero-based index.
Fix: Use items[len(items) - 1] or the preferred items[-1].
Expecting len() to Return a Position
Problem: Code treats the result of len(items) as an index.
Cause: len() returns an item count, not an item's position.
Fix: For a count of n, remember that indexes run from 0 through n - 1.
Getting IndexError for the Last Item
Problem: Code uses items[-1] or items[len(items) - 1] and receives IndexError.
Cause: The list is empty and therefore has no valid positions.
Fix: Guard the access with if items:.
Calling len Incorrectly
Problem: Code writes len without parentheses or omits the argument.
Fix: Call the function with a sized object, such as len(my_list). Parentheses and the list argument are required.
Quick Reference
len(my_list) # number of elements
count = len(my_list) # store the integer result
my_list[len(my_list) - 1] # last item via calculated index
my_list[-1] # last item via negative indexing
if my_list: # check that the list is not empty
print(my_list[-1])
Use len(my_list) when you need the number of elements. Use my_list[-1] when you need the final element directly, and always check that the list is non-empty before accessing a last item.