Question

How to Get the Length of a List in Python

pythonlist

Question

How can I get the number of elements in a Python list?

For example, given this list:

items = ["apple", "orange", "banana"]

How do I determine that it contains 3 items?

Short Answer

By the end of this page, you will understand how to count the number of elements in a Python list using len(), how it works, when to use it, and the most common mistakes beginners make.

Concept

In Python, the standard way to get the number of elements in a list is to use the built-in len() function.

items = ["apple", "orange", "banana"]
print(len(items))  # 3

len() returns how many elements are stored in a collection-like object, such as:

  • lists
  • strings
  • tuples
  • dictionaries
  • sets

For a list, len() tells you how many items are inside it.

This matters because counting items is a very common task in programming. You often need to:

  • check whether a list is empty
  • validate user input
  • limit results
  • loop based on how many items exist
  • compare two collections

In Python, len() is preferred over manually counting because it is clear, short, and idiomatic.

Mental Model

Think of a list as a row of labeled boxes:

items = ["apple", "orange", "banana"]

Each box holds one value:

  • box 1 → "apple"
  • box 2 → "orange"
  • box 3 → "banana"

len(items) asks:

How many boxes are there?

It does not ask:

  • what the values are
  • what the last index is
  • how many characters are in the words

It only counts how many elements the list contains.

Take Quiz

Syntax and Examples

The basic syntax is:

len(list_name)

Example 1: Basic list length

items = ["apple", "orange", "banana"]
count = len(items)
print(count)

Output:

3

Here, len(items) returns 3 because the list has three elements.

Example 2: Empty list

items = []
print(len(items))

Output:

0

An empty list has length 0.

Example 3: Using length in a condition

cart = ["apple", "banana"]

if len(cart) > 0:
    print("The cart has items.")

This is useful when you want to check whether a list contains anything.

Example 4: Nested lists

data = [[1, 2], [3, 4], [5, 6]]
print(len(data))

Output:

3

The outer list contains three elements. Each element happens to be another list, but len(data) only counts the top-level items.

Step by Step Execution

Consider this example:

items = ["apple", "orange", "banana"]
count = len(items)
print(count)

Step by step:

  1. Python creates a list with three strings:

    • "apple"
    • "orange"
    • "banana"
  2. That list is stored in the variable items.

  3. len(items) is evaluated.

    • Python checks how many elements are in the list.
    • It finds 3 elements.
  4. The value 3 is assigned to count.

  5. print(count) outputs:

3

Another trace example

numbers = [10, 20, 30, 40]
print(len(numbers))

Execution:

  1. Create a list with four numbers.
  2. Call len(numbers).
  3. Python returns 4.
  4. print() displays 4.

Real World Use Cases

Getting the length of a list is used constantly in real programs.

Common scenarios

  • Shopping cart systems
    • Count how many products a user has added.
  • Form processing
    • Check how many validation errors were found.
  • API results
    • Count how many records were returned from a request.
  • File processing
    • Count how many lines, rows, or parsed items were collected.
  • Game development
    • Track how many players, enemies, or moves exist.
  • Task management apps
    • Show the number of completed or pending tasks.

Example: API-style data

users = ["Ava", "Noah", "Mia"]
print(f"Found {len(users)} users")

Example: Validation

errors = []

if not errors:
    print("No validation errors")
else:
    print(f"There are {len(errors)} errors")
Take Quiz

Real Codebase Usage

In real codebases, developers rarely call len() in isolation. They use it as part of larger patterns.

1. Validation

tags = ["python", "beginner"]

if len(tags) > 5:
    print("Too many tags")

2. Guard clauses

items = []

if len(items) == 0:
    print("Nothing to process")

A common Python style improvement is:

if not items:
    print("Nothing to process")

3. Comparing collections

a = [1, 2, 3]
b = [4, 5]

if len(a) > len(b):
    print("a has more items")

4. Limiting output

results = ["r1", "r2", "r3", "r4"]

if len(results) > 3:
    print("Too many results to show at once")

5. Loops with indexes

items = ["apple", "orange", "banana"]

for i in range(len(items)):
    print(i, items[i])

This works, though in many cases Python developers prefer direct iteration:

for item in items:
    print(item)

Common Mistakes

Here are common mistakes beginners make when working with list length in Python.

1. Using .length like in other languages

Broken code:

items = ["apple", "orange", "banana"]
print(items.length)

This fails because Python lists do not have a .length property.

Correct code:

print(len(items))

2. Confusing length with the last index

items = ["apple", "orange", "banana"]
print(len(items))  # 3

The last valid index is 2, not 3.

Indexes start at 0:

  • items[0] → "apple"
  • items[1] → "orange"
  • items[2] → "banana"

3. Off-by-one errors in loops

Broken code:

items = ["apple", "orange", "banana"]

for i in range(len(items) + 1):
    print(items[i])

This causes an IndexError when i becomes 3.

Correct code:

for i in range(len(items)):
    print(items[i])

4. Calling len() on a number

Broken code:

count = 3
print(len(count))

len() works on sized collections, not plain integers.

5. Using len() when a truthy check is simpler

This works:

if len(items) == 0:
    print("Empty")

But Python often prefers:

if not items:
    print("Empty")

Both are valid, but the second is more idiomatic.

Comparisons

Here are some useful comparisons around len() and related ideas.

ConceptPython ExampleWhat it Means
List lengthlen(items)Number of elements in the list
String lengthlen(name)Number of characters in the string
Dictionary lengthlen(data)Number of key-value pairs
Set lengthlen(tags)Number of unique elements

len(items) vs last index

ExpressionMeaning
len(items)How many items are in the list
len(items) - 1Index of the last item, if the list is not empty

len(items) == 0 vs not items

StyleMeaningCommon Use
len(items) == 0List is emptyExplicit, beginner-friendly
not itemsList is emptyMore idiomatic Python

Direct loop vs index loop

ApproachExampleUsually Better When
Direct iterationfor item in items:You only need values
Index-based iterationfor i in range(len(items)):You need positions or indexes
Take Quiz

Cheat Sheet

# Get list length
len(items)

# Example
items = ["apple", "orange", "banana"]
print(len(items))  # 3

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

# Check if list is empty
if len(items) == 0:
    print("Empty")

# More Pythonic empty check
if not items:
    print("Empty")

# Last index of a non-empty list
last_index = len(items) - 1

Rules to remember

  • Use len(list_name) to count items in a list.
  • Python lists do not use .length.
  • len(items) is the count, not the last index.
  • For a list with 3 items, valid indexes are 0, 1, and 2.
  • len([]) returns 0.

Edge cases

  • Empty list → len([]) is 0
  • Nested lists → len() counts only the outer list unless you inspect inner lists separately
  • len() does not work on plain integers

FAQ

How do I get the number of items in a Python list?

Use the built-in len() function:

len(items)

What does len() return for an empty list?

It returns 0.

Is there a .length property for Python lists?

No. Python uses len(items), not items.length.

Does len() count nested items too?

No. It only counts the top-level elements in the list.

data = [[1], [2], [3]]
print(len(data))  # 3

What is the difference between len(items) and len(items) - 1?

len(items) is the number of elements. len(items) - 1 is the last valid index for a non-empty list.

Should I use len(items) == 0 or not items?

Both work. not items is more idiomatic in Python, but len(items) == 0 can be clearer for beginners.

Take Quiz

Mini Project

Description

Build a small Python script that manages a shopping list and displays how many items are currently in it. This helps you practice using len() in a realistic, beginner-friendly context.

Goal

Create a script that stores a list of shopping items, prints the full list, and shows the total number of items.

Requirements

  • Create a Python list with at least three shopping items.
  • Print the list contents.
  • Use len() to print the total number of items.
  • Add one more item to the list and print the updated count.
Take Quiz

Keep learning

Related questions

View more