4Geeks chosen to deliver AI education in the Bahamas alongside Harvard, Oxford, and Columbia.See more

How to Get the Length of a List in Python?

By 4Geeks

Count the items of any list with len(), check if it is empty, count nested lists and unique values, and fix the errors you will meet along the way.

6 min readLast updated
Python list length icon

How do you get the length of a list in Python?

Short answer: use the built-in len() function. len(fruits) returns how many items the list has. An empty list returns 0.

python
fruits = ["apple", "banana", "cherry"]
 
print(len(fruits))   # 3
print(len([]))       # 0

Lists have no .length property and no .len() method like in other languages. In Python you always write len(my_list).

len() counts the items of a list, returns 0 when it is empty, only counts the top level of a nested list and fails with numbers.

Every way to count items in Python

What you wantCodeResult
Items in a listlen(["apple", "banana", "cherry"])3
Check if a list is emptyif not fruits:True when empty
Every item in a nested listsum(len(x) for x in [[1, 2], [3, 4, 5]])5
Unique itemslen(set([3, 8, 8, 5, 3]))3
How many times a value appears[3, 8, 8, 5, 3].count(8)2
Items that meet a conditionsum(1 for n in nums if n > 4)3
Characters in a stringlen("hello")5
Keys in a dict, items in a tuple or setlen({"a": 1, "b": 2}), len((1, 2, 3))2, 3
Rows of a pandas DataFramelen(df) or df.shape[0]Number of rows
Elements of a NumPy arrayarr.size (all), len(arr) (first dimension)6, 2

Use len() with lists

len() works with any list, whatever the items are. It counts items, not values, so None, "" and 0 also count:

python
print(len([1, None, "", 0]))   # 4

The length changes when you add or remove items:

python
fruits = ["apple", "banana", "cherry"]
 
fruits.append("kiwi")
print(len(fruits))   # 4
 
fruits.pop()
print(len(fruits))   # 3

len() is instant even with millions of items, because Python keeps the size stored in the list. You don't need to save it in a variable to make your code faster.

Career · AI Engineering

You already count items in Python, now build with AI

From zero to junior AI Engineer: Python, data, AI agents and RAG with mentors and real projects.

Use the length to reach items by position

Positions start at 0, so the last item is at len(fruits) - 1. Asking for fruits[len(fruits)] fails:

python
fruits = ["apple", "banana", "cherry"]
 
print(fruits[len(fruits) - 1])   # cherry
print(fruits[-1])                # cherry, the short way
print(fruits[len(fruits)])       # IndexError: list index out of range

To loop with the position, enumerate() is clearer than range(len(...)):

python
for i, fruit in enumerate(fruits):
    print(i, fruit)
# 0 apple
# 1 banana
# 2 cherry

Check if a list is empty

An empty list counts as False, so you don't need len():

python
cart = []
 
if not cart:
    print("empty")   # empty

if len(cart) == 0: also works, but if not cart: is the usual style in Python.

Count the items in a nested list

len() only counts the top level. A list with two lists inside has a length of 2, however many items each one has:

python
nested = [[1, 2], [3, 4, 5]]
 
print(len(nested))                    # 2
print(sum(len(x) for x in nested))    # 5

If the lists can go deeper, use a small recursive function:

python
def count_all(items):
    return sum(count_all(x) if isinstance(x, list) else 1 for x in items)
 
print(count_all([1, [2, [3, 4]], 5]))   # 5

Count unique values, repeats and matches

python
nums = [3, 8, 8, 5, 3]
 
print(len(set(nums)))                # 3  unique values
print(nums.count(8))                 # 2  times 8 appears
print(sum(1 for n in nums if n > 4)) # 3  items greater than 4

len() with strings, dicts, tuples, sets and ranges

len() works with every Python collection:

python
print(len("hello"))            # 5  characters
print(len({"a": 1, "b": 2}))   # 2  keys
print(len((1, 2, 3)))          # 3
print(len({1, 2, 2, 3}))       # 3  sets drop repeats
print(len(range(10)))          # 10

Your own classes can work with len() too. Define a __len__ method that returns an integer.

Length in NumPy and pandas

python
import numpy as np
import pandas as pd
 
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(len(arr))     # 2  rows (first dimension)
print(arr.size)     # 6  every element
print(arr.shape)    # (2, 3)
 
df = pd.DataFrame({"name": ["Ana", "Luis", "Eva"]})
print(len(df))      # 3  rows
print(df.shape)     # (3, 1)  rows and columns

In pandas, len() counts every row, including empty values. df["col"].count() counts only the values that are not empty.

Use AI to work with list lengths

An assistant like ChatGPT, Claude or GitHub Copilot can explain an error or write the counting code for your data. These three prompts are ready to copy.

1. Explain an error

In Python, this line: [paste your line]
gives this error: [paste the error].
Explain why and show me how to fix it.

2. Count what you need

I have this Python list: [paste a short example].
Show me how to count [all the items / the unique items / the items that ...]
and explain each line.

3. Check a dataset

I have a pandas DataFrame with these columns: [list the columns].
Show me how to count the rows, the empty values in each column
and the rows where [your condition].

Run every answer yourself and check the numbers with a small example you can count by hand.

Learn with a mentor

From Python lists to AI applications

In the 4Geeks AI Engineering career program you start with no experience and finish with AI agents and RAG systems in your portfolio.

Common problems with list length in Python

What you seeWhy it happensFix
AttributeError: 'list' object has no attribute 'length'Python lists have no .lengthUse len(my_list)
AttributeError: 'list' object has no attribute 'len'len is a function, not a methodWrite len(my_list), not my_list.len()
TypeError: object of type 'int' has no len()Numbers have no lengthUse len(str(number)) to count digits
TypeError: object of type 'NoneType' has no len()The variable is None, often from a function with no returnCheck the value, or use len(items or [])
TypeError: object of type 'generator' has no len()Generators don't know their sizelen(list(gen)) or sum(1 for _ in gen)
IndexError: list index out of rangeThe last position is len(list) - 1Use my_list[-1] or range(len(my_list))
len() of a nested list is smaller than expectedIt only counts the top levelsum(len(x) for x in nested)
Free download

Python list length in a 2-page cheat sheet

len(), empty lists, nested lists, unique values and matches, len() with other collections, NumPy and pandas, common errors and prompts for ChatGPT, Claude or Copilot. Free, in PDF.

Python list length cheat sheet

2 pages · PDF · 4Geeks

  • Every way to count items in a list
  • How to count nested lists, unique values and matches
  • Common errors and prompts to solve them with AI

Get it free

Your PDF right away

Frequently asked questions about Python list length

Want to go from your first Python lists to building AI applications, with real projects and mentors?

See the AI Engineering program